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:contestWebsite.Registration.java

@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    VelocityEngine ve = new VelocityEngine();
    ve.setProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, "html/pages, html/snippets");
    ve.init();//w w w  .  ja va  2s .  c  o  m
    VelocityContext context = new VelocityContext();
    Pair<Entity, UserCookie> infoAndCookie = init(context, req);
    boolean loggedIn = (boolean) context.get("loggedIn");

    if (loggedIn && !infoAndCookie.y.isAdmin()) {
        context.put("registrationError", "You are already registered.");
    }

    SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
    dateFormat.setTimeZone(TimeZone.getTimeZone("GMT+6"));

    String endDateStr = dateFormat.format(new Date());
    String startDateStr = dateFormat.format(new Date());

    Entity contestInfo = infoAndCookie.x;
    if (contestInfo != null) {
        endDateStr = (String) contestInfo.getProperty("endDate");
        startDateStr = (String) contestInfo.getProperty("startDate");

        Date endDate = new Date();
        Date startDate = new Date();
        try {
            endDate = dateFormat.parse(endDateStr);
            startDate = dateFormat.parse(startDateStr);
        } catch (ParseException e) {
            e.printStackTrace();
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Incorrect date format");
        }

        if (loggedIn && infoAndCookie.y.isAdmin()) {
            context.put("registrationError", "");
        } else if (new Date().after(endDate) || new Date().before(startDate)) {
            context.put("registrationError", "Registration is closed, please try again next year.");
        } else {
            context.put("registrationError", "");
        }

        context.put("price", contestInfo.getProperty("price"));
        context.put("classificationQuestion", contestInfo.getProperty("classificationQuestion"));
        context.put("publicKey", contestInfo.getProperty("publicKey"));
    } else {
        context.put("registrationError", "Registration is closed, please try again next year.");
        context.put("price", 5);
    }

    HttpSession sess = req.getSession(true);
    sess.setAttribute("nocaptcha", loggedIn && infoAndCookie.y.isAdmin());
    context.put("nocaptcha", loggedIn && infoAndCookie.y.isAdmin());

    String userError = req.getParameter("userError");
    String passwordError = req.getParameter("passwordError");
    String captchaError = req.getParameter("captchaError");

    if (sess != null && (userError + passwordError + captchaError).contains("1")) {
        context.put("coach".equals(sess.getAttribute("registrationType")) ? "coach" : "student", true);
        context.put("account", "yes".equals(sess.getAttribute("account")));

        String[] propNames = { "schoolName", "name", "email", "updated", "classification", "studentData",
                "schoolLevel" };
        for (String propName : propNames) {
            context.put(propName, sess.getAttribute(propName));
        }
    } else {
        context.put("account", true);
        context.put("schoolName", "");
        context.put("name", "");
        context.put("email", "");
        context.put("studentData", "[]");
    }

    if ("1".equals(req.getParameter("updated"))) {
        context.put("updated", true);
        if (sess != null) {
            Map<String, Object> props = (Map<String, Object>) sess.getAttribute("props");
            if (props != null) {
                ArrayList<String> regData = new ArrayList<String>();
                for (Entry<String, Object> prop : props.entrySet()) {
                    String key = prop.getKey();
                    if (!key.equals("account") && PropNames.names.get(key) != null) {
                        regData.add(
                                "<dt>" + PropNames.names.get(key) + "</dt>\n<dd>" + prop.getValue() + "</dd>");
                    }
                }

                Collections.sort(regData);
                context.put("regData", regData);
                context.put("studentData", sess.getAttribute("studentData"));

                sess.invalidate();
            }
        }
    }

    context.put("userError", userError);
    context.put("passwordError", passwordError);
    context.put("captchaError", captchaError);
    if (userError != null || passwordError != null || captchaError != null) {
        context.put("error", true);
    }

    context.put("Level", Level.class);

    close(context, ve.getTemplate("registration.html"), resp);
}

From source file:net.naijatek.myalumni.modules.common.presentation.action.SecurityAction.java

public ActionForward login(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    HttpSession session = request.getSession(false);
    Integer counter = (Integer) session.getAttribute("loginCounter");
    int loginCounter = 0;
    String currentIP = request.getRemoteAddr();
    ActionMessages errors = new ActionMessages();

    LoginForm loginForm = (LoginForm) form;

    String username = loginForm.getMemberUserName();
    String password = loginForm.getMemberPassword();

    MemberVO token = null;/* w  ww .j a v  a2  s  . com*/
    LoginHistoryVO accessHistory = null;

    ServletContext sCtx = request.getSession().getServletContext();
    WebApplicationContext wCtx = WebApplicationContextUtils.getWebApplicationContext(sCtx);
    MyAlumniUserContainer container = (MyAlumniUserContainer) wCtx.getBean("userContainer");

    logger.info("Login attempt --> , [ " + username + " ][ " + currentIP + "]");

    if (counter == null) {
        session.setAttribute("loginCounter", new Integer(loginCounter));
        session.setAttribute("loginUserCounter", username);
    } else {
        loginCounter = counter.intValue();
    }

    // login and store it in the session
    accessHistory = createAccessHistory(request, username);

    try {
        token = securityService.login(username, password, currentIP);
        token.setLoginSuccessfull(true);
        accessHistory.setLoginStatus(BaseConstants.LOGIN_PASS);
        accessHistory.setReasonCode(ReasonCodes.SUCCESS);

        // Prompt user to change password
        if (token.getPromptChange().equals(BaseConstants.BOOLEAN_YES)) {

            loginForm.setMemberUserName(token.getMemberUserName());
            loginForm.setMemberPassword("");
            loginForm.setMemberTempPassword("");
            loginForm.setMemberPasswordConfirm("");

            session.invalidate();
            errors.add(BaseConstants.INFO_KEY, new ActionMessage("errors.login.resetpassword"));
            saveMessages(request, errors);
            accessHistory.setLoginStatus(BaseConstants.LOGIN_FAIL);
            accessHistory.setReasonCode(ReasonCodes.CHANGE_PASSWORD);
            securityService.addAccessTrail(accessHistory);
            return mapping.findForward(BaseConstants.FWD_EXPIRED_PASSWORD);
        }

        // Cant find roles
        if (token.getIsAdmin() == null || (!token.getIsAdmin().equals(BaseConstants.BOOLEAN_NO)
                & !token.getIsAdmin().equals(BaseConstants.BOOLEAN_YES))) {
            errors.add(BaseConstants.ERROR_KEY, new ActionMessage("errors.login.role"));
            saveMessages(request, errors);
            accessHistory.setLoginStatus(BaseConstants.LOGIN_FAIL);
            accessHistory.setReasonCode(ReasonCodes.NO_ROLES_FOUND);
            securityService.addAccessTrail(accessHistory);
            return mapping.getInputForward();
        }

    } catch (UserAccountException e) {
        //token.setLoginSuccessfull(false);
        if (e.getExceptionReason() == NotLoginException.ACCOUNT_DEACTIVATED) {
            session.invalidate();
            errors.add(BaseConstants.WARN_KEY, new ActionMessage("errors.account.deactivated"));
            saveMessages(request, errors);
            logger.info("ACCOUNT DEACTIVATED : " + username);
            accessHistory.setLoginStatus(BaseConstants.LOGIN_FAIL);
            accessHistory.setReasonCode(ReasonCodes.ACCOUNT_DEACTIVATED);
            securityService.addAccessTrail(accessHistory);
            return mapping.getInputForward();
        }
        if (e.getExceptionReason() == NotLoginException.ACCOUNT_DELETED) {
            session.invalidate();
            errors.add(BaseConstants.WARN_KEY, new ActionMessage("errors.account.deleted"));
            saveMessages(request, errors);
            accessHistory.setLoginStatus(BaseConstants.LOGIN_FAIL);
            accessHistory.setReasonCode(ReasonCodes.ACCOUNT_DELETED);
            securityService.addAccessTrail(accessHistory);
            return mapping.getInputForward();
        }
        if (e.getExceptionReason() == NotLoginException.ACCOUNT_LOCKED) {
            session.invalidate();
            errors.add(BaseConstants.WARN_KEY, new ActionMessage("errors.account.locked"));
            saveMessages(request, errors);
            logger.info("ACCOUNT LOCKED : " + username);
            accessHistory.setLoginStatus(BaseConstants.LOGIN_FAIL);
            accessHistory.setReasonCode(ReasonCodes.ACCOUNT_LOCKED);
            securityService.addAccessTrail(accessHistory);
            return mapping.getInputForward();
        } else if (e.getExceptionReason() == NotLoginException.WRONG_PASSWORD) {
            //session.invalidate();
            errors.add(BaseConstants.WARN_KEY, new ActionMessage("errors.password.mismatch", currentIP));
            saveMessages(request, errors);
            logger.info("INVALID PASSWORD : " + username);
            accessHistory.setLoginStatus(BaseConstants.LOGIN_FAIL);
            accessHistory.setReasonCode(ReasonCodes.INVALID_CREDENTIAL);

            // increment failed login counter
            // if the same user contineously try to login , counter increases
            // if a diff user from the prev user, but same session, counter resets
            if (username.equals(session.getAttribute("loginUserCounter"))) {
                loginCounter++;
            } else {
                loginCounter = 0;
                session.setAttribute("loginCounter", new Integer(loginCounter));
            }

            // Maximum number of time a user can try to login unsuccessfully
            int userMaxLogin = Integer.parseInt(getSysProp().getValue("USER_MAX_LOGIN"));
            if (loginCounter >= userMaxLogin) {
                logger.warn(username + " : User has exceeded maximum number of login attempts");
                logger.warn("User account has been disabled. Please contact System Administrator");

                // deactivating user account
                if (securityService.lockMemberAccount(username)) {
                    session.invalidate();
                    errors.add(BaseConstants.WARN_KEY, new ActionMessage("errors.account.locked"));
                    logger.info("ACCOUNT LOCKED :  IP: (" + currentIP + ") " + username);
                    accessHistory.setLoginStatus(BaseConstants.LOGIN_FAIL);
                    accessHistory.setReasonCode(ReasonCodes.ACCOUNT_LOCKED);
                    securityService.addAccessTrail(accessHistory);
                    return mapping.getInputForward();
                }
            } else {
                session.setAttribute("loginCounter", new Integer(loginCounter));
            }

            securityService.addAccessTrail(accessHistory);
            return mapping.getInputForward();
        } else if (e.getExceptionReason() == NotLoginException.WRONG_USERNAME) {
            logger.info("INVALID USERNAME: IP: (" + currentIP + ") " + username
                    + " User login attempt has failed. Count = " + loginCounter);
            accessHistory.setLoginStatus(BaseConstants.LOGIN_FAIL);
            accessHistory.setReasonCode(ReasonCodes.ACCOUNT_INVALID);
            errors.add(BaseConstants.WARN_KEY, new ActionMessage("errors.password.mismatch"));
            saveMessages(request, errors);
            logger.info("UNSUCCESSFULL FWD_LOGIN - Invalid login  IP: (" + currentIP + ") " + username);
            accessHistory.setLoginStatus(BaseConstants.LOGIN_FAIL);
            accessHistory.setReasonCode(ReasonCodes.INVALID_CREDENTIAL);
            securityService.addAccessTrail(accessHistory);
            return mapping.getInputForward();
        } else if (e.getExceptionReason() == NotLoginException.ACCOUNT_UNAPPROVED) {
            errors.add(BaseConstants.WARN_KEY, new ActionMessage("errors.account.notapproved"));
            saveMessages(request, errors);
            logger.info("UNSUCCESSFULL FWD_LOGIN - Account not approved yet. :  IP: (" + currentIP + ") "
                    + username);
            accessHistory.setLoginStatus(BaseConstants.LOGIN_FAIL);
            accessHistory.setReasonCode(ReasonCodes.ACCOUNT_UNAPPROVED);
            securityService.addAccessTrail(accessHistory);
            return mapping.getInputForward();
        }

    }

    if (token.isLoginSuccessfull()) {
        //clear out any old session info
        session = request.getSession(false);
        if (session != null) {
            session.invalidate();
        }

        // Create a new session for this user
        session = request.getSession(true);

        // place users container in session
        container.setToken(token);
        setSessionUserContainer(request, container);

        setupOtherTasks(request, container, token);

        int sessionTimeout = setupSessionTimeout(session);

        // adding the user user the list of online users
        token.setLastRequestTime(new Date());
        OnlineUserManager manager = OnlineUserManager.getInstance();
        manager.addOnlineUser(token, sessionTimeout);
        //sCtx.setAttribute("onlineusers", manager.getOnlineUsers(sessionTimeout));
        setServletContextObject(request, "onlineusers", manager.getOnlineUsers(sessionTimeout));

        session.setAttribute(BaseConstants.IS_ONLINE, BaseConstants.BOOLEAN_YES);
        session.setAttribute(BaseConstants.IS_ADMIN, token.getIsAdmin());

        // ADMIN
        String context = request.getPathInfo();

        if (context.startsWith("/admin/") && token.getIsAdmin().equals(BaseConstants.BOOLEAN_YES)) {
            setupAdminDesktop(request, memService, classNewsService, privateMessageService);
            securityService.addAccessTrail(accessHistory);
        } else if (context.startsWith("/member/") && (token.getIsAdmin().equals(BaseConstants.BOOLEAN_YES)
                || token.getIsAdmin().equals(BaseConstants.BOOLEAN_NO))) {
            securityService.addAccessTrail(accessHistory);
        } else {
            accessHistory.setLoginStatus(BaseConstants.LOGIN_FAIL);
            accessHistory.setReasonCode(ReasonCodes.ACCOUNT_UNAUTHORIZED);
            securityService.addAccessTrail(accessHistory);
            errors.add(BaseConstants.WARN_KEY, new ActionMessage("errors.account.notenoughrights"));
            saveMessages(request, errors);
            logger.info("ACCOUNT UNAUTHORIZED :  IP: (" + currentIP + ") " + username);
            return mapping.getInputForward();
        }

        return mapping.findForward(BaseConstants.FWD_SUCCESS);

    } else {
        errors.add(BaseConstants.FATAL_KEY, new ActionMessage("errors.technical.difficulty"));
        saveMessages(request, errors);
        return mapping.getInputForward();
    }
}

From source file:com.sammyun.controller.shop.LoginController.java

/**
 * ??//from  ww  w  . ja  v  a 2  s .  c  om
 */
@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");
    }
    checkLockedStatus(member, setting);

    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");
        }
    }
    updateLoginStatus(request, member);

    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:Servlets.ServletRegistro.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
 *
 * @param request servlet request/*  w  w  w.ja v a  2s .co  m*/
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, FileUploadException, Exception {
    response.setContentType("text/html;charset=UTF-8");
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    HttpSession valida = null;
    if (isMultipart) {
        FileItemFactory file_factory = new DiskFileItemFactory();
        ServletFileUpload servlet_up = new ServletFileUpload(file_factory);
        List items = servlet_up.parseRequest(request);
        String urlImg = "";
        Hashtable datosUsuario = new Hashtable();
        for (int i = 0; i < items.size(); i++) {
            FileItem item = (FileItem) items.get(i);
            if (!item.isFormField()) {
                urlImg = item.getName();
                if (!urlImg.equals("")) {
                    String dir = getServletContext().getRealPath("/");
                    String dir2 = dir.replaceAll("web", "img");
                    String dir3 = dir2.replaceAll("build", "web");
                    dir3.concat("imgUsuarios/");
                    File fileFoto = new File(dir3, item.getName());
                    item.write(fileFoto);
                }
            } else {
                datosUsuario.put(item.getFieldName(), item.getString());
            }
        }
        if (urlImg.equals("")) {
            urlImg = (String) datosUsuario.get("imgdefecto");
        }
        user = new Usuario(0, (String) datosUsuario.get("nombre"), (String) datosUsuario.get("apellido"),
                Integer.parseInt((String) datosUsuario.get("dni")), false, (String) datosUsuario.get("user"),
                (String) datosUsuario.get("pass"), (String) datosUsuario.get("email"),
                (String) datosUsuario.get("telefono"), urlImg);
        RequestDispatcher rd = getServletContext().getRequestDispatcher(
                "/ServletValidaUser?user=" + user.getUser() + "&email=" + user.getEmail());
        rd.include(request, response);
        valida = request.getSession(true);
        if (valida.getAttribute("usuarioValid") == null) {
            try {
                ctrlUsuario.registraUsuario(user);
                user = ctrlLogin.validaUsuario(user);
                HttpSession sesion = request.getSession(true);
                sesion.setAttribute("usuarioLog", user);
                RequestDispatcher aux = request.getRequestDispatcher("/principal.jsp");
                aux.forward(request, response);
            } catch (SQLException ex) {
                Logger.getLogger(ServletRegistro.class.getName()).log(Level.SEVERE, null, ex);
            }
        } else {
            valida.invalidate();
        }
    } else {
        String idUsuario = request.getParameter("idUsuario");
        ArrayList<Usuario> list = null;
        boolean flag = false;
        if (idUsuario == null) {
            flag = true;
        } else {
            if (!idUsuario.equals("0")) {
                list = new ArrayList<>();
                list.add(ctrlUsuario.traePorId(Integer.parseInt(idUsuario)));
                flag = true;
            }
            if (flag) {
                list = ctrlUsuario.listarUsuarios();
                String json = new Gson().toJson(list);
                response.setContentType("application/json");
                response.setCharacterEncoding("UTF-8");
                response.getWriter().write(json);
            }
        }
    }
}

From source file:org.yawlfoundation.yawl.resourcing.jsf.SessionBean.java

/**********************************************************************************/

// PAGE NAVIGATION METHODS //

// logs out of session //
public void doLogout() {
    _rm.logout(sessionhandle);/*  w  ww  . jav  a 2  s .  c om*/
    setEditedParticipantToNull();
    getApplicationBean().removeLiveUser(userid);
    setUserid(null);

    FacesContext context = FacesContext.getCurrentInstance();
    if (context != null) { // if null, session already destroyed
        HttpSession session = (HttpSession) context.getExternalContext().getSession(false);
        session.invalidate();
    }
}

From source file:gov.nih.nci.ncicb.cadsr.common.security.LogoutServlet.java

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    //unlock all forms locked by this session
    HttpSession session = request.getSession();
    String logTjsp = getServletConfig().getInitParameter("LogthroughJSP");
    if (logTjsp != null && !logTjsp.equals(""))
        LOGTHROUGH_JSP = logTjsp;//  www . ja v  a2s . c o m

    String lojsp = getServletConfig().getInitParameter("LogoutJSP");
    if (lojsp != null && !lojsp.equals(""))
        LOGOUT_JSP = lojsp;
    String authjsp = getServletConfig().getInitParameter("ErrorJSP");
    if (authjsp != null && !authjsp.equals(""))
        AUTHORIZATION_ERROR_JSP = authjsp;

    if (!request.getContextPath().contains("CDEBrowser")) {
        getApplicationServiceLocator(session.getServletContext()).findLockingService()
                .unlockFormByUser(request.getRemoteUser());
    }
    synchronized (SessionUtils.sessionObjectCache) {
        log.error("LogoutServlet.doPost at start:" + TimeUtils.getEasternTime());
        String error = request.getParameter("authorizationError");
        String forwardUrl;
        //// GF29128 Begin. D.An, 20130729. 
        String un = (String) session.getAttribute("myUsername");
        ;
        ////   if (un == null)
        ////      un = "viewer";
        System.out.println("logoutServlet: " + session.getAttribute("myUsername"));
        if (error == null) {
            if (un.equals("viewer"))
                forwardUrl = LOGTHROUGH_JSP;
            //// GF29128  end.      
            else
                forwardUrl = LOGOUT_JSP;
        } else {
            forwardUrl = AUTHORIZATION_ERROR_JSP;
        }

        if ((session != null) && isLoggedIn(request)) {
            for (int i = 0; i < logoutKeys.length; i++) {
                session.removeAttribute(logoutKeys[i]);
            }

            //remove formbuilder specific objects
            //TODO has to be moved to an action
            Collection keys = (Collection) session.getAttribute(FormBuilderConstants.CLEAR_SESSION_KEYS);
            if (keys != null) {
                Iterator it = keys.iterator();
                while (it.hasNext()) {
                    session.removeAttribute((String) it.next());
                }
            }
            HashMap allMap = new HashMap();
            allMap.put(CaDSRConstants.GLOBAL_SESSION_KEYS, copyAllsessionKeys(session));
            allMap.put(CaDSRConstants.GLOBAL_SESSION_MAP, copyAllsessionObjects(session));
            SessionUtils.addToSessionCache(session.getId(), allMap);
            forwardUrl = forwardUrl + "?" + CaDSRConstants.PREVIOUS_SESSION_ID + "=" + session.getId();
            session.invalidate();
        }

        RequestDispatcher dispacher = request.getRequestDispatcher(forwardUrl);
        dispacher.forward(request, response);
        log.error("LogoutServlet.doPost at end:" + TimeUtils.getEasternTime());
    }
}

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

@RequestMapping(value = "/logsaccess", method = { RequestMethod.GET, RequestMethod.POST })
public ModelAndView accessLogs(HttpSession session) {

    String role = (String) session.getAttribute("Role");
    if (role == null) {
        ModelAndView model = new ModelAndView();
        model.setViewName("index");
        return model;
    } else if (role.equals("ADMIN")) {
        ModelAndView model = new ModelAndView();
        String directorypath = "C:\\AppLogs\\";
        File folder = new File(directorypath);
        File[] listOfFiles = folder.listFiles();

        for (int i = 0; i < listOfFiles.length; i++) {
            if (listOfFiles[i].isFile()) {
                model.addObject("file1", listOfFiles[0].getName());
            }/*from   w ww.  ja  v  a  2  s  .com*/
        }
        model.setViewName("viewlogs");
        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;
    }
}

From source file:com.citrix.cpbm.portal.fragment.controllers.AbstractAuthenticationController.java

@RequestMapping(value = { "/{userParam}/loggedout", "{userParam}/j_spring_security_logout" })
public String loggedout(@PathVariable String userParam, ModelMap map, HttpSession session,
        HttpServletResponse response, HttpServletRequest request) {
    logger.debug("###Entering in loggedout(response) method");
    String showSuffixControl = "false";
    String suffixControlType = "textbox";
    List<String> suffixList = null;
    if (config.getValue(Names.com_citrix_cpbm_username_duplicate_allowed).equals("true")) {
        showSuffixControl = "true";
        if (config.getValue(Names.com_citrix_cpbm_login_screen_tenant_suffix_dropdown_enabled).equals("true")) {
            suffixControlType = "dropdown";
            suffixList = tenantService.getSuffixList();
        }/*from ww  w .j a  v  a 2  s. co m*/
    }
    map.addAttribute("showSuffixControl", showSuffixControl);
    map.addAttribute("suffixControlType", suffixControlType);
    map.addAttribute("suffixList", suffixList);
    if (config.getBooleanValue(Configuration.Names.com_citrix_cpbm_portal_directory_service_enabled)
            && config.getValue(Names.com_citrix_cpbm_directory_mode).equals("pull")) {
        map.addAttribute("directoryServiceAuthenticationEnabled", "true");
    }
    if (config.getValue(Names.com_citrix_cpbm_public_catalog_display).equals("true")
            && channelService.getDefaultServiceProviderChannel() != null) {
        map.addAttribute("showAnonymousCatalogBrowsing", "true");
    }
    map.addAttribute("showLanguageSelection", "true");
    map.addAttribute("supportedLocaleList", this.getLocaleDisplayName(listSupportedLocales()));
    map.addAttribute("logout", true);
    String redirect = null;
    Enumeration<String> en = session.getAttributeNames();
    while (en.hasMoreElements()) {
        String attr = en.nextElement();
        session.removeAttribute(attr);
    }
    Cookie cookie = new Cookie("JforumSSO", "");
    cookie.setMaxAge(0);
    cookie.setPath("/");
    response.addCookie(cookie);
    if (request.getRequestedSessionId() != null && request.isRequestedSessionIdValid()) {
        // create logout notification begins
        User user = userService.get(userParam);
        String message = "logged.out";
        String messageArgs = user.getUsername();
        eventService.createEvent(new Date(), user, message, messageArgs, Source.PORTAL, Scope.USER,
                Category.ACCOUNT, Severity.INFORMATION, true);
    }
    session.invalidate();
    if (config.getAuthenticationService().compareToIgnoreCase(CAS) == 0) {
        try {
            redirect = StringUtils.isEmpty(config.getCasLogoutUrl()) ? null
                    : config.getCasLogoutUrl() + "?service="
                            + URLEncoder.encode(config.getCasServiceUrl(), "UTF-8");
        } catch (UnsupportedEncodingException e) {
            logger.error("Exception encoding: " + redirect, e);
        }
        if (redirect == null) {
            throw new InternalError("CAS authentication required, but login url not set");
        }
    }

    SecurityContextHolder.getContext().setAuthentication(null);
    // ends
    logger.debug("###Exiting loggedout(response) method");
    return redirect == null ? "redirect:/j_spring_security_logout" : "redirect:" + redirect;
}

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

@RequestMapping(value = { "**/reqchangeaccount" }, method = { RequestMethod.GET, RequestMethod.POST })
public ModelAndView reqchangeaccount(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;
    }//from  www .  jav a2 s  .c  o  m

    else if (role.equals("USER") || role.equals("MERCHANT")) {
        ModelAndView model = new ModelAndView();
        ModifyUsersHandler handler = new ModifyUsersHandler();
        if (request.getParameter("accountchange") != null) {

            handler.updateaccountrequest((String) request.getSession().getAttribute("USERNAME"),
                    request.getParameter("managername"), request.getParameter("accountnumber"));
            model.addObject("status", "Request Successfully Sent");
            model.setViewName("searchaccounttochange");

        }
        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;
    }
}

From source file:be.fedict.eid.dss.webapp.ProtocolExitServlet.java

@Override
protected void handleRequest(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {

    LOG.debug("doGet");
    HttpSession httpSession = request.getSession();
    String entryContextPath = ProtocolEntryServlet.retrieveProtocolServiceEntryContextPath(httpSession);
    DSSProtocolService protocolService = super.findProtocolService(entryContextPath);
    if (null == protocolService) {
        error(request, response, "no protocol service active", null);
        return;// ww  w . ja  v  a  2  s .co  m
    }

    DocumentRepository documentRepository = new DocumentRepository(httpSession);

    byte[] signedDocument = documentRepository.getSignedDocument();

    if (null != signedDocument) {
        String mimetype = documentRepository.getDocumentContentType();
        String email = documentRepository.getEmail();
        this.mailManager.sendSignedDocument(email, "en", mimetype, signedDocument);
    }

    String documentId = documentRepository.getDocumentId();
    if (null != documentId && null != signedDocument) {

        // update document entry
        try {
            this.documentService.update(documentId, signedDocument);
        } catch (DocumentNotFoundException e) {
            error(request, response, "Document not found!", null);
            return;
        }
    } else if (null != documentId) {

        // document artifact needs to be removed, user cancelled signing...
        this.documentService.remove(documentId);
    }

    SignatureStatus signatureStatus = documentRepository.getSignatureStatus();
    X509Certificate signerCertificate = documentRepository.getSignerCertificate();

    BrowserPOSTResponse returnResponse;
    try {
        returnResponse = protocolService.handleResponse(signatureStatus, signedDocument, documentId,
                signerCertificate, httpSession, request, response);
    } catch (Exception e) {
        LOG.error("protocol error: " + e.getMessage(), e);
        httpSession.setAttribute(this.protocolErrorMessageSessionAttributeInitParam, e.getMessage());
        response.sendRedirect(request.getContextPath() + this.protocolErrorPageInitParam);
        return;
    }
    if (null != returnResponse) {
        /*
         * This means that the protocol service wants us to construct some
         * Browser POST response towards the Service Provider landing site.
         */
        LOG.debug("constructing generic Browser POST response...");
        httpSession.setAttribute(this.responseActionSessionAttributeInitParam, returnResponse.getActionUrl());
        httpSession.setAttribute(this.responseAttributesSessionAttributeInitParam,
                returnResponse.getAttributes());
        response.sendRedirect(request.getContextPath() + this.protocolResponsePostPageInitParam);
        return;
    }
    LOG.debug("protocol service managed its own protocol response");
    /*
     * Clean-up the session here as it is no longer used after this point.
     */
    httpSession.invalidate();
}