Example usage for javax.servlet.http HttpSession removeAttribute

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

Introduction

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

Prototype

public void removeAttribute(String name);

Source Link

Document

Removes the object bound with the specified name from this session.

Usage

From source file:net.latin.server.GwtBaseAction.java

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

public String execute() throws Exception {

    try {/*w ww  .j  a v  a2  s.  co  m*/
        // Store the request & response objects in thread-local storage.
        //

        // save globals in the user thread local
        // (antes del readContent porque si falla doUnexpectedFailure()
        // espera que el response este seteado en UserContext)
        UserContext userContext = UserContext.getInstance();
        userContext.setRequest(request);
        userContext.setResponse(response);

        // Read the request fully.
        //
        String requestPayload = readContent(request);

        userContext.setRequestPayload(requestPayload);

        if (SpringUtils.useSpringPersistenceTemplates()) {
            /**
             * Execute the gwt method inside a spring transaction
             */
            SpringUtils.getTransactionTemplate().execute(new TransactionCallbackWithoutResult() {
                @Override
                protected void doInTransactionWithoutResult(TransactionStatus transactionStatus) {
                    try {

                        // save the transactionStatus in the ThreadLocal
                        UserContext.getInstance().setTransactionStatus(transactionStatus);

                        /**
                         * Process gwt method inside the transaction
                         */
                        executeGwtMethod();

                        // check for declared LnwTransactionException in
                        // session
                        HttpSession session = UserContext.getInstance().getRequest().getSession(false);
                        if (session != null) {
                            LnwTransactionException trEx = (LnwTransactionException) session
                                    .getAttribute(GwtUseCase.LNW_TRANSACTION_EXCEPTION_KEY);
                            // if it was loaded in session, rollback
                            // transaction (see LnwTransactionException
                            // class)
                            if (trEx != null) {
                                session.removeAttribute(GwtUseCase.LNW_TRANSACTION_EXCEPTION_KEY);
                                rollbackTransaction(transactionStatus);
                            }
                        }

                        // Catchs exceptions and rollback
                    } catch (Exception e) {
                        rollbackTransaction(transactionStatus);

                        // throws another exception, with the originial
                        // wrapped, to be catched by gwt
                        throw new RuntimeException(e);
                    }
                }
            });
        } else {
            /**
             * Process gwt method (and let the subclass determines if a
             * transaction handling is needed)
             */
            executeGwtMethod();
        }
    } catch (SocketException se) {
        // Vemos si no es que el cliente cerro el browser y se perdio la
        // conexion
        // antes de que termine de enviar todo el response.
        // Es burda, pero es la unica manera que encontre de detectar estos
        // casos.
        if (!se.getMessage().toLowerCase().contains("connection reset")) {
            throw se;
        }
    } catch (Throwable e) {
        // Give a subclass a chance to either handle the exception or
        // rethrow it
        doUnexpectedFailure(e);
    } finally {
        // null the thread-locals to avoid holding request/response
        //

        // clear user context
        UserContext.getInstance().clear();

    }

    // no forward requeried
    return null;
}

From source file:com.sun.faban.harness.webclient.XFormServlet.java

/**
 * A get request starts a new form.// www.java  2s  .  c om
 *
 * @param request The servlet request
 * @param response The servlet response
 * @throws ServletException Error in request handling
 * @throws IOException Error doing other IO
 */
public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    HttpSession session = request.getSession(true);
    Adapter adapter = null;

    String templateFile = (String) session.getAttribute("faban.submit.template");
    String styleSheet = (String) session.getAttribute("faban.submit.stylesheet");

    String srcURL = new File(templateFile).toURI().toString();

    logger.finer("benchmark.template: " + srcURL);
    session.removeAttribute("faban.submit.template");
    session.removeAttribute("faban.submit.stylesheet");

    try {
        String requestURI = request.getRequestURI();
        String formURI = null;
        String contextPath = request.getContextPath();
        String benchPath = contextPath + "/bm_submit/";
        if (requestURI.startsWith(benchPath)) {
            int idx = requestURI.indexOf('/', benchPath.length());
            String benchName = requestURI.substring(benchPath.length(), idx);
            String formName = requestURI.substring(idx + 1);
            formURI = com.sun.faban.harness.common.Config.FABAN_HOME + "benchmarks/" + benchName + "/META-INF/"
                    + formName;
        } else {
            StringBuffer buffer = new StringBuffer(request.getScheme());
            buffer.append("://");
            buffer.append(request.getServerName());
            buffer.append(":");
            buffer.append(request.getServerPort());
            buffer.append(request.getContextPath());
            buffer.append(request.getParameter("form"));
            formURI = buffer.toString();
        }

        if (formURI == null) {
            throw new IOException("Resource not found: " + formURI);
        }
        logger.finer("Form URI: " + formURI);

        String css = request.getParameter("css");
        String actionURL = response.encodeURL(request.getRequestURI());
        logger.finer("actionURL: " + actionURL);

        // Find the base URL used by Faban. We do not use Config.FABAN_URL
        // because this base URL can vary by the interface name the Faban
        // master is accessed in this session. Otherwise it is identical.
        StringBuffer baseURL = request.getRequestURL();
        int uriLength = baseURL.length() - requestURI.length() + contextPath.length();
        baseURL.setLength(++uriLength); // Add the ending slash

        adapter = new Adapter();
        if (configFile != null && configFile.length() > 0)
            adapter.setConfigPath(configFile);

        File xsl = null;
        if (styleSheet != null)
            xsl = new File(styleSheet);

        if (xsl != null && xsl.exists()) {
            adapter.xslPath = xsl.getParent();
            adapter.stylesheet = xsl.getName();
        } else {
            adapter.xslPath = xsltDir;
            adapter.stylesheet = "faban.xsl";
        }

        adapter.baseURI = baseURL.toString();
        adapter.formURI = formURI;
        adapter.actionURL = actionURL;
        adapter.beanCtx.put("chiba.web.uploadDir", uploadDir);
        adapter.beanCtx.put("chiba.useragent", request.getHeader("User-Agent"));
        adapter.beanCtx.put("chiba.web.request", request);
        adapter.beanCtx.put("chiba.web.session", session);
        adapter.beanCtx.put("benchmark.template", srcURL);

        if (css != null) {
            adapter.CSSFile = css;
            logger.fine("using css stylesheet: " + css);
        }

        Map servletMap = new HashMap();
        servletMap.put(ChibaAdapter.SESSION_ID, session.getId());
        adapter.beanCtx.put(ChibaAdapter.SUBMISSION_RESPONSE, servletMap);

        Enumeration params = request.getParameterNames();
        while (params.hasMoreElements()) {
            String s = (String) params.nextElement();
            //store all request-params we don't use in the beanCtx map
            if (!(s.equals("form") || s.equals("xslt") || s.equals("css") || s.equals("action_url"))) {
                String value = request.getParameter(s);
                adapter.beanCtx.put(s, value);
                logger.finer("added request param '" + s + "' to beanCtx");
            }
        }
        adapter.init();
        adapter.execute();

        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        adapter.generator.setOutput(out);
        adapter.buildUI();
        session.setAttribute("chiba.adapter", adapter);
        out.close();
    } catch (Exception e) {
        logger.log(Level.SEVERE, "Exception processing XForms", e);
        shutdown(adapter, session, e, request, response);
    }
}

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

/**
* Performs the logging out of users//from  w w w  .  java  2  s  .  co m
*
* @param mapping ActionMapping
* @param form ActionForm
* @param request HttpServletRequest
* @param response HttpServletResponse
* @throws Exception
* @return ActionForward
*/
public ActionForward logout(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    HttpSession session = request.getSession(true);

    int sessionTimeout = setupSessionTimeout(session);
    MemberVO token = getCurrentLoggedInUser(request);
    if (token != null) {
        OnlineUserManager manager = OnlineUserManager.getInstance();
        manager.removeOnlineUser(token.getMemberUserName());
        ServletContext sCtx = request.getSession().getServletContext();
        sCtx.setAttribute("onlineusers", manager.getOnlineUsers(sessionTimeout));
    }

    if (session != null) {
        session.removeAttribute(BaseConstants.USER_CONTAINER);
        logger.info("User successfully logged out...");
        session.invalidate();
    }

    return (mapping.findForward(BaseConstants.FWD_SUCCESS));
}

From source file:com.highcharts.export.controller.ExportController.java

@RequestMapping(method = { RequestMethod.POST, RequestMethod.GET })
public HttpEntity<byte[]> exporter(@RequestParam(value = "svg", required = false) String svg,
        @RequestParam(value = "type", required = false) String type,
        @RequestParam(value = "filename", required = false) String filename,
        @RequestParam(value = "width", required = false) String width,
        @RequestParam(value = "scale", required = false) String scale,
        @RequestParam(value = "options", required = false) String options,
        @RequestParam(value = "globaloptions", required = false) String globalOptions,
        @RequestParam(value = "constr", required = false) String constructor,
        @RequestParam(value = "callback", required = false) String callback,
        @RequestParam(value = "callbackHC", required = false) String callbackHC,
        @RequestParam(value = "async", required = false, defaultValue = "false") Boolean async,
        @RequestParam(value = "jsonp", required = false, defaultValue = "false") Boolean jsonp,
        HttpServletRequest request, HttpSession session)
        throws ServletException, InterruptedException, SVGConverterException, NoSuchElementException,
        PoolException, TimeoutException, IOException, ZeroRequestParameterException {

    MimeType mime = getMime(type);
    String randomFilename = null;
    String jsonpCallback = "";
    boolean isAndroid = request.getHeader("user-agent") != null
            && request.getHeader("user-agent").contains("Android");

    if ("GET".equalsIgnoreCase(request.getMethod())) {

        // Handle redirect downloads for Android devices, these come in without request parameters
        String tempFile = (String) session.getAttribute("tempFile");
        session.removeAttribute("tempFile");

        if (tempFile != null && !tempFile.isEmpty()) {
            logger.debug("filename stored in session, read and stream from filesystem");
            String basename = FilenameUtils.getBaseName(tempFile);
            String extension = FilenameUtils.getExtension(tempFile);

            return getFile(basename, extension);

        }//w ww  . j a v  a 2s.c om
    }

    // check for visitors who don't know this domain is really only for the exporting service ;)
    if (request.getParameterMap().isEmpty()) {
        throw new ZeroRequestParameterException();
    }

    /* Most JSONP implementations use the 'callback' request parameter and this overwrites
     * the original callback parameter for chart creation with Highcharts. If JSONP is
     * used we recommend using the requestparameter callbackHC as the callback for Highcharts.
     * store the callback method name and reset the callback parameter,
     * otherwise it will be used when creation charts
     */
    if (jsonp) {
        async = true;
        jsonpCallback = callback;
        callback = null;

        if (callbackHC != null) {
            callback = callbackHC;
        }
    }

    if (isAndroid || MimeType.PDF.equals(mime) || async) {
        randomFilename = createRandomFileName(mime.name().toLowerCase());
    }

    /* If randomFilename is not null, then we want to save the filename in session, in case of GET is used later on*/
    if (isAndroid) {
        logger.debug("storing randomfile in session: " + FilenameUtils.getName(randomFilename));
        session.setAttribute("tempFile", FilenameUtils.getName(randomFilename));
    }

    String output = convert(svg, mime, width, scale, options, constructor, callback, globalOptions,
            randomFilename);
    ByteArrayOutputStream stream;

    HttpHeaders headers = new HttpHeaders();

    if (async) {
        String link = TempDir.getDownloadLink(randomFilename);
        stream = new ByteArrayOutputStream();
        if (jsonp) {
            StringBuilder sb = new StringBuilder(jsonpCallback);
            sb.append("('");
            sb.append(link);
            sb.append("')");
            stream.write(sb.toString().getBytes("utf-8"));
            headers.add("Content-Type", "text/javascript; charset=utf-8");
        } else {
            stream.write(link.getBytes("utf-8"));
            headers.add("Content-Type", "text/html; charset=UTF-8");
        }
    } else {
        headers.add("Content-Type", mime.getType() + "; charset=utf-8");
        if (randomFilename != null && randomFilename.equals(output)) {
            stream = writeFileToStream(randomFilename);
        } else {
            boolean base64 = !mime.getExtension().equals("svg");
            stream = outputToStream(output, base64);
        }
        filename = getFilename(filename);
        headers.add("Content-Disposition",
                "attachment; filename=" + filename.replace(" ", "_") + "." + mime.name().toLowerCase());
    }

    headers.setContentLength(stream.size());

    return new HttpEntity<byte[]>(stream.toByteArray(), headers);
}

From source file:org.jasig.cas.support.oauth.web.OAuth20CallbackAuthorizeActionController.java

@Override
protected ModelAndView handleRequestInternal(final HttpServletRequest request,
        final HttpServletResponse response) throws Exception {
    final HttpSession session = request.getSession();

    // get action
    final String action = request.getParameter(OAuthConstants.OAUTH20_APPROVAL_PROMPT_ACTION);
    LOGGER.debug("{} : {}", OAuthConstants.OAUTH20_APPROVAL_PROMPT_ACTION, action);

    if (!action.equalsIgnoreCase(OAuthConstants.OAUTH20_APPROVAL_PROMPT_ACTION_ALLOW)) {
        LOGGER.error("{} was not allowed.", OAuthConstants.OAUTH20_APPROVAL_PROMPT_ACTION);
        // callback url with error
        String callbackUrl = (String) session.getAttribute(OAuthConstants.OAUTH20_CALLBACKURL);
        callbackUrl = OAuthUtils.addParameter(callbackUrl, OAuthConstants.ERROR, OAuthConstants.ACCESS_DENIED);
        LOGGER.debug("{} : {}", OAuthConstants.OAUTH20_CALLBACKURL, callbackUrl);
        return OAuthUtils.redirectTo(callbackUrl);
    }/*from w  ww . j a  va  2  s  . co m*/

    // retrieve client id from session
    String clientId = (String) session.getAttribute(OAuthConstants.OAUTH20_CLIENT_ID);
    LOGGER.debug("{} : {}", OAuthConstants.OAUTH20_CLIENT_ID, clientId);
    session.removeAttribute(OAuthConstants.OAUTH20_CLIENT_ID);
    if (StringUtils.isBlank(clientId)) {
        LOGGER.error("{} is missing from the session and can not be retrieved.",
                OAuthConstants.OAUTH20_CLIENT_ID);
        return new ModelAndView(OAuthConstants.ERROR_VIEW);
    }

    // retrieve callback url from session
    String callbackUrl = (String) session.getAttribute(OAuthConstants.OAUTH20_CALLBACKURL);
    LOGGER.debug("{} : {}", OAuthConstants.OAUTH20_CALLBACKURL, callbackUrl);
    session.removeAttribute(OAuthConstants.OAUTH20_CALLBACKURL);
    if (StringUtils.isBlank(callbackUrl)) {
        LOGGER.error("{} is missing from the session and can not be retrieved.",
                OAuthConstants.OAUTH20_CALLBACKURL);
        return new ModelAndView(OAuthConstants.ERROR_VIEW);
    }

    // retrieve state from session (csrf equivalent)
    final String state = (String) session.getAttribute(OAuthConstants.OAUTH20_STATE);
    LOGGER.debug("{} : {}", OAuthConstants.OAUTH20_STATE, state);
    session.removeAttribute(OAuthConstants.OAUTH20_STATE);
    if (state != null) {
        callbackUrl = OAuthUtils.addParameter(callbackUrl, OAuthConstants.STATE, state);
    }

    String loginTicketId = (String) session.getAttribute(OAuthConstants.OAUTH20_LOGIN_TICKET_ID);
    final OAuthRegisteredService registeredService = OAuthUtils.getRegisteredOAuthService(this.servicesManager,
            clientId);
    session.removeAttribute(OAuthConstants.OAUTH20_LOGIN_TICKET_ID);
    if (registeredService == null) {
        LOGGER.error("Unknown {} : {}", OAuthConstants.CLIENT_ID, clientId);
        return new ModelAndView(OAuthConstants.ERROR_VIEW);
    }

    Service service = new SimpleWebApplicationServiceImpl(callbackUrl);
    final ServiceTicket serviceTicket = centralAuthenticationService.grantServiceTicket(loginTicketId, service);

    // callback url with code (encrypted service ticket)
    callbackUrl = OAuthUtils.addParameter(callbackUrl, OAuthConstants.CODE,
            cipherExecutor.encode(serviceTicket.getId()));
    LOGGER.debug("{} : {}", OAuthConstants.OAUTH20_CALLBACKURL, callbackUrl);

    return OAuthUtils.redirectTo(callbackUrl);
}

From source file:net.unicon.academus.apps.blogger.plugin.AcademusSSOPlugin.java

/**
 * Authenticate the user if their authentication session variable is not present
 *
 * @param httpServletRequest Request/*w  w  w . jav  a  2 s . c om*/
 * @param httpServletResponse Response
 * @param context Context
 * @param blogUser User information
 * @return <code>true</code> if the user is authenticated,
 * <code>false</code> otherwise
 */
protected boolean authenticateUser(HttpServletRequest httpServletRequest,
        HttpServletResponse httpServletResponse, Map context, BlogUser blogUser) {
    Blog blog = blogUser.getBlog();
    BlojsomUtils.setNoCacheControlHeaders(httpServletResponse);
    HttpSession httpSession = httpServletRequest.getSession();

    String username = httpServletRequest.getParameter(BLOJSOM_ADMIN_PLUGIN_USERNAME_PARAM);
    String password = httpServletRequest.getParameter(BLOJSOM_ADMIN_PLUGIN_PASSWORD_PARAM);

    // Check for the authenticated key and if not authenticated,
    // look for a "username" and "password" parameter.
    if (httpSession
            .getAttribute(blog.getBlogAdminURL() + "_" + BLOJSOM_ADMIN_PLUGIN_AUTHENTICATED_KEY) == null) {
        if (username == null || password == null || "".equals(username) || "".equals(password)) {
            _logger.debug("No username/password provided or username/password was empty");
            return false;
        }

    } else if (username != null && !("".equals(username) && httpSession
            .getAttribute(blog.getBlogAdminURL() + "_" + BLOJSOM_ADMIN_PLUGIN_USERNAME_KEY).equals(username))) {
        httpSession.removeAttribute(blog.getBlogAdminURL() + "_" + BLOJSOM_ADMIN_PLUGIN_AUTHENTICATED_KEY);
        httpSession.removeAttribute(BLOJSOM_ADMIN_PLUGIN_USERNAME);
        httpSession.removeAttribute(BLOJSOM_USER_AUTHENTICATED);

        if (username == null || password == null || "".equals(username) || "".equals(password)) {
            _logger.debug("No username/password provided or username/password was empty");
            return false;
        }
    } else {
        return ((Boolean) httpSession
                .getAttribute(blog.getBlogAdminURL() + "_" + BLOJSOM_ADMIN_PLUGIN_AUTHENTICATED_KEY))
                        .booleanValue();
    }

    // Let's attempt to authenticate the user.
    try {
        _authorizationProvider.loadAuthenticationCredentials(blogUser);
        _authorizationProvider.authorize(blogUser, null, username, password);
        httpSession.setAttribute(blog.getBlogAdminURL() + "_" + BLOJSOM_ADMIN_PLUGIN_AUTHENTICATED_KEY,
                Boolean.TRUE);
        httpSession.setAttribute(blog.getBlogAdminURL() + "_" + BLOJSOM_ADMIN_PLUGIN_USERNAME_KEY, username);
        httpSession.setAttribute(BLOJSOM_ADMIN_PLUGIN_USERNAME, username);
        httpSession.setAttribute(BLOJSOM_USER_AUTHENTICATED, Boolean.TRUE);

        _logger.debug("Passed authentication for username: " + username);

        return true;
    } catch (BlojsomException e) {
        _logger.debug("Failed authentication for username: " + username);
        addOperationResultMessage(context, "Failed authentication for username: " + username);

        return false;
    }

}

From source file:org.mitre.openid.connect.filter.PromptFilter.java

/**
 * //from   w  ww.  j a v a2s. co m
 */
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
        throws IOException, ServletException {

    HttpServletRequest request = (HttpServletRequest) req;
    HttpServletResponse response = (HttpServletResponse) res;

    if (!Strings.isNullOrEmpty(request.getParameter("prompt"))) {
        // we have a "prompt" parameter

        if (request.getParameter("prompt").equals("none")) {
            logger.info("Client requested no prompt");
            // see if the user's logged in
            Authentication auth = SecurityContextHolder.getContext().getAuthentication();

            if (auth != null) {
                // user's been logged in already (by session management)
                // we're OK, continue without prompting
                chain.doFilter(req, res);
            } else {
                // user hasn't been logged in, we need to "return an error"
                logger.info("User not logged in, no prompt requested, returning 403 from filter");
                response.sendError(HttpServletResponse.SC_FORBIDDEN, "Access Denied");
                return;
            }
        } else if (request.getParameter("prompt").equals("login")) {

            // first see if the user's already been prompted in this session
            HttpSession session = request.getSession();
            if (session.getAttribute(PROMPTED) == null) {
                // user hasn't been PROMPTED yet, we need to check             

                session.setAttribute(PROMPT_REQUESTED, Boolean.TRUE);

                // see if the user's logged in
                Authentication auth = SecurityContextHolder.getContext().getAuthentication();
                if (auth != null) {
                    // user's been logged in already (by session management)
                    // log them out and continue
                    SecurityContextHolder.getContext().setAuthentication(null);
                    chain.doFilter(req, res);
                } else {
                    // user hasn't been logged in yet, we can keep going since we'll get there
                    chain.doFilter(req, res);
                }
            } else {
                // user has been PROMPTED, we're fine

                // but first, undo the prompt tag
                session.removeAttribute(PROMPTED);
                chain.doFilter(req, res);
            }
        } else {
            // prompt parameter is a value we don't care about, not our business
            chain.doFilter(req, res);
        }

    } else if (!Strings.isNullOrEmpty(request.getParameter("max_age"))) {
        // TODO: issue #450
        String maxAge = request.getParameter("max_age");
        HttpSession session = request.getSession();
        Date authTime = (Date) session.getAttribute(AuthenticationTimeStamper.AUTH_TIMESTAMP);

        Date now = new Date();
        if (authTime != null) {
            Integer max = Integer.parseInt(maxAge);
            long seconds = (now.getTime() - authTime.getTime()) / 1000;
            if (seconds > max) {
                // session is too old, log the user out and continue
                SecurityContextHolder.getContext().setAuthentication(null);
            }
        }

        chain.doFilter(req, res);
    } else {
        // no prompt parameter, not our business
        chain.doFilter(req, res);
    }

}

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

@RequestMapping({ "/login", "/portal", "/" })
public String login(HttpServletRequest request, ModelMap map, HttpSession session) {
    logger.debug("###Entering in login(req,map,session) method");

    boolean loginFailed = request.getParameter(LOGIN_FAILED_PARAM) != null;

    if (!loginFailed && request.getUserPrincipal() != null) {
        map.clear();/*  w ww  . j  a v a  2  s.  c  o  m*/
        return "redirect:/portal/home";
    }

    if (session.getAttribute("email_verified") != null) {
        map.addAttribute("email_verified", session.getAttribute("email_verified"));
        session.removeAttribute("email_verified");
    }
    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();
        }
    }
    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("selected_language", request.getParameter("lang"));
    String redirect = null;
    boolean loggedOut = request.getParameter(LOGOUT_PARAM) != null;
    final Throwable ex = (Throwable) session.getAttribute(WebAttributes.AUTHENTICATION_EXCEPTION);

    // capture previous CAPTCHA position
    Boolean captchaRequiredSessionObj = (Boolean) session
            .getAttribute(CaptchaAuthenticationFilter.CAPTCHA_REQUIRED);

    // Get last user
    String username = (String) session
            .getAttribute(UsernamePasswordAuthenticationFilter.SPRING_SECURITY_LAST_USERNAME_KEY);

    // this as spring does a text-escape when it saves this attribute
    final String uUsername = HtmlUtils.htmlUnescape(username);

    if (loginFailed) {
        String error = " "
                + messageSource.getMessage("error.auth.username.password.invalid", null, request.getLocale());

        try {
            User user = privilegeService.runAsPortal(new PrivilegedAction<User>() {

                @Override
                public User run() {
                    User user = userService.getUserByParam("username", uUsername, false);

                    // All user writes here.
                    // Every time there is a login failure but not invalid CAPTCHA,
                    // we update failed login attempts for the user
                    if (!(ex instanceof CaptchaValidationException) && !(ex instanceof LockedException)
                            && !(ex instanceof IpRangeValidationException)) {
                        user.setFailedLoginAttempts(user.getFailedLoginAttempts() + 1);
                    }

                    int attempts = user.getFailedLoginAttempts();

                    // Also locking the root user and quite easily too. Clearly this
                    // needs an eye!
                    if (attempts >= config.getIntValue(
                            Names.com_citrix_cpbm_accountManagement_security_logins_lockThreshold)) {
                        user.setEnabled(false);
                    }

                    return user;
                }
            });

            int attempts = user.getFailedLoginAttempts();
            if (attempts >= config
                    .getIntValue(Names.com_citrix_cpbm_accountManagement_security_logins_captchaThreshold)) {
                session.setAttribute(CaptchaAuthenticationFilter.CAPTCHA_REQUIRED, true);
            }
        } catch (NoSuchUserException e) {
            // map.addAttribute("showCaptcha", true);
        }

        captchaRequiredSessionObj = (Boolean) session
                .getAttribute(CaptchaAuthenticationFilter.CAPTCHA_REQUIRED);

        map.addAttribute("loginFailed", loginFailed);
        String lastUsername = uUsername;

        if (config.getValue(Names.com_citrix_cpbm_username_duplicate_allowed).equals("true")) {
            if (!lastUsername.equals("root") && !lastUsername.equals("")) {
                lastUsername = lastUsername.substring(0, lastUsername.lastIndexOf('@'));
            }
        }
        map.addAttribute("lastUser", lastUsername);

        // Compose error string
        if (ex instanceof DisabledException) {
            error = " " + messageSource.getMessage("error.auth.username.password.invalid", null,
                    request.getLocale());
        } else if (ex instanceof CaptchaValidationException) {
            error = " " + messageSource.getMessage("error.auth.captcha.invalid", null, request.getLocale());
        } else if (ex instanceof IpRangeValidationException) {
            error = " " + messageSource.getMessage("error.auth.username.password.invalid", null,
                    request.getLocale());
        } else if (ex instanceof LockedException) {
            error = " " + messageSource.getMessage("error.auth.username.password.invalid", null,
                    request.getLocale());
        } else if (ex instanceof BadCredentialsException) {
            if (ex.getMessage() != null && ex.getMessage().length() > 0) {
                // error = " " + ex.getMessage();
                error = " " + messageSource.getMessage("error.auth.username.password.invalid", null,
                        request.getLocale());
            }
        } else if (ex instanceof AuthenticationException) {
            error = " " + messageSource.getMessage("error.auth.username.password.invalid", null,
                    request.getLocale());
        } else {
            logger.error("Error occurred in authentication", ex);
            error = " " + messageSource.getMessage("error.auth.unknown", null, request.getLocale());
        }

        if (captchaRequiredSessionObj != null && captchaRequiredSessionObj == true
                && !(ex instanceof CaptchaValidationException) && !(ex instanceof LockedException)) {
            error += " " + messageSource.getMessage("error.auth.account.may.locked", null, request.getLocale());
        }

        map.addAttribute("error", error);

    }

    if (loggedOut) {
        map.addAttribute("logout", loggedOut);
    }

    // This could come from session or from user
    if (captchaRequiredSessionObj != null && captchaRequiredSessionObj.booleanValue()
            && !Boolean.valueOf(config.getValue(Names.com_citrix_cpbm_use_intranet_only))) {
        map.addAttribute("showCaptcha", true);
        map.addAttribute("recaptchaPublicKey", config.getRecaptchaPublicKey());
    }

    map.addAttribute(TIME_OUT, request.getParameter(TIME_OUT) != null);
    map.addAttribute(VERIFY, request.getParameter(VERIFY) != null);
    logger.debug("###Exiting login(req,map,session) method");

    if (config.getAuthenticationService().compareToIgnoreCase(CAS) == 0) {
        try {
            redirect = StringUtils.isEmpty(config.getCasLoginUrl()) ? null
                    : config.getCasLoginUrl() + "?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");
        }
    }
    return redirect == null ? "auth.login" : "redirect:" + redirect;
}

From source file:com.skilrock.lms.web.scratchService.gameMgmt.common.GameUploadAction.java

public String displayTicketsUploadInventory() {
    HttpSession session = getRequest().getSession();
    session.removeAttribute("VERIFIED_PACKSERIES_FLAGBEAN_LIST");
    try {/*from w  w w.j  a  v a2  s .  c  om*/
        warehouseMap = new CommonFunctionsHelper().fetchWarehouseMap();
    } catch (Exception e) {
        // TODO: handle exception
    }
    return SUCCESS;
}

From source file:com.linecorp.sample.login.application.controller.WebController.java

/**
 * <p>Redirect Page from LINE Platform</p>
 * <p>Login Type is to log in on any desktop or mobile website
 *//*  w w  w .  ja v a  2s . c o m*/
@RequestMapping("/auth")
public String auth(HttpSession httpSession, @RequestParam(value = "code", required = false) String code,
        @RequestParam(value = "state", required = false) String state,
        @RequestParam(value = "scope", required = false) String scope,
        @RequestParam(value = "error", required = false) String error,
        @RequestParam(value = "errorCode", required = false) String errorCode,
        @RequestParam(value = "errorMessage", required = false) String errorMessage) {

    if (logger.isDebugEnabled()) {
        logger.debug("parameter code : " + code);
        logger.debug("parameter state : " + state);
        logger.debug("parameter scope : " + scope);
        logger.debug("parameter error : " + error);
        logger.debug("parameter errorCode : " + errorCode);
        logger.debug("parameter errorMessage : " + errorMessage);
    }

    if (error != null || errorCode != null || errorMessage != null) {
        return "redirect:/loginCancel";
    }
    ;

    if (!state.equals(httpSession.getAttribute(LINE_WEB_LOGIN_STATE))) {
        return "redirect:/sessionError";
    }
    ;

    httpSession.removeAttribute(LINE_WEB_LOGIN_STATE);
    AccessToken token = lineAPIService.accessToken(code);
    if (logger.isDebugEnabled()) {
        logger.debug("scope : " + token.scope);
        logger.debug("access_token : " + token.access_token);
        logger.debug("token_type : " + token.token_type);
        logger.debug("expires_in : " + token.expires_in);
        logger.debug("refresh_token : " + token.refresh_token);
    }
    httpSession.setAttribute(ACCESS_TOKEN, token);
    return "redirect:/success";
}