Example usage for javax.servlet.http Cookie Cookie

List of usage examples for javax.servlet.http Cookie Cookie

Introduction

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

Prototype

public Cookie(String name, String value) 

Source Link

Document

Constructs a cookie with the specified name and value.

Usage

From source file:com.identityconcepts.shibboleth.WSFedLoginHandler.java

/**
 * set cookie for pass-through/*w w  w . j  av a  2 s  . c  o  m*/
 * cookieDomain can be configured in the handler config
 *
 * @param  path   path to which the client should return the cookie
 */
public static Cookie createCookie(String path) {
    Cookie cookie = new Cookie(COOKIE_NAME, "1");
    cookie.setMaxAge(60 * 60 * 24 * 365);
    cookie.setPath(path);
    cookie.setSecure(true);
    // use cookieDomain if set
    if (!((cookieDomain == null) || (cookieDomain == ""))) {
        cookie.setDomain(cookieDomain);
    }
    return cookie;
}

From source file:com.salesmanager.core.util.www.SalesManagerInterceptor.java

private MerchantStore setMerchantStore(HttpServletRequest req, HttpServletResponse resp, String merchantId)
        throws Exception {

    // different merchantId
    int iMerchantId = 1;

    try {//from ww  w .j  a  v  a  2 s . c o  m
        iMerchantId = Integer.parseInt(merchantId);
    } catch (Exception e) {
        log.error("Cannot parse merchantId to Integer " + merchantId);
    }

    // get MerchantStore
    MerchantService mservice = (MerchantService) ServiceFactory.getService(ServiceFactory.MerchantService);
    MerchantStore mStore = mservice.getMerchantStore(iMerchantId);

    if (mStore == null) {
        // forward to error page
        log.error("MerchantStore does not exist for merchantId " + merchantId);
        return null;
    }

    req.getSession().setAttribute("STORE", mStore);
    req.setAttribute("STORE", mStore);

    //get store configuration for template
    ReferenceService rservice = (ReferenceService) ServiceFactory.getService(ServiceFactory.ReferenceService);
    Map storeConfiguration = rservice.getModuleConfigurationsKeyValue(mStore.getTemplateModule(),
            mStore.getCountry());

    if (storeConfiguration != null) {
        req.getSession().setAttribute("STORECONFIGURATION", storeConfiguration);
    }

    Cookie c = new Cookie("STORE", merchantId);
    c.setMaxAge(365 * 24 * 60 * 60);
    resp.addCookie(c);

    if (!RefCache.isLoaded()) {
        RefCache.createCache();
    }

    return mStore;

}

From source file:org.apache.hadoop.yarn.server.webproxy.WebAppProxyServlet.java

private static Cookie makeCheckCookie(ApplicationId id, boolean isSet) {
    Cookie c = new Cookie(getCheckCookieName(id), String.valueOf(isSet));
    c.setPath(ProxyUriUtils.getPath(id));
    c.setMaxAge(60 * 60 * 2); //2 hours in seconds
    return c;/*from  w w  w  .j  a va2 s.  c  o m*/
}

From source file:memedb.httpd.MemeDBHandler.java

protected Credentials getCredentials(HttpServletRequest request, HttpServletResponse response)
        throws IOException {
    Credentials cred = null;/*w ww .j  a v a 2  s .com*/

    if (request.getRequestURI().equals("/_auth")) {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        log.debug("login attempt for {}", username);
        if (!allowAnonymous && "anonymous".equals(username)) {
            sendNoAuthError(response, "Bad username / password combination");
            return null;
        }
        if (username != null) {
            if (password == null) {
                password = "";
            }
            if (allowAnonymous && allowAnonymousAsSa && "anonymous".equals(username)) {
                return new SACredentials("anonymous", "", timeout);
            }
            cred = memeDB.getAuthentication().authenticate(username, password);
            if (cred != null) {
                if (request.getParameter("setcookie") == null
                        || request.getParameter("setcookie").toLowerCase().equals("false")) {
                    Cookie cookie = new Cookie(COOKIE_ID, cred.getToken());
                    cookie.setMaxAge(timeout);
                    response.addCookie(cookie);
                }
                return cred;
            } else {
                log.warn("Bad login attempt for {}", username);
                sendNoAuthError(response, "Bad username / password combination");
                return null;
            }
        }
    }

    Cookie[] cookies = request.getCookies();
    if (cookies != null) {
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals(COOKIE_ID)) {
                cred = memeDB.getAuthentication().getCredentialsFromToken(cookie.getValue());
                if (cred != null) {
                    log.debug("Got credentials from cookie token: {}", cookie.getValue());
                    return cred;
                }
            }
        }
    }

    String param = request.getParameter("token");
    if (param != null && !param.equals("")) {
        cred = memeDB.getAuthentication().getCredentialsFromToken(param);
        if (cred != null) {
            log.debug("Authenticated as {} => {} via Req param", cred.getUsername(), cred.getToken());
            addCredentialedCookie(response, cred);
            return cred;
        }
    }

    String headerparam = request.getHeader("MemeDB-Token");
    if (headerparam != null && !headerparam.equals("")) {
        log.info("Attempting authentication with token {}", headerparam);
        cred = memeDB.getAuthentication().getCredentialsFromToken(headerparam);
        if (cred != null) {
            log.info("Got credentials!");
            log.debug("Authenticated as {} => {} via HTTP-Header", cred.getUsername(), cred.getToken());
            addCredentialedCookie(response, cred);
            return cred;
        }
    }

    String authHeader = request.getHeader("Authorization");
    if (authHeader != null) {
        String[] authSplit = authHeader.split(" ");
        if (authSplit.length == 2) {
            String userpass = new String(Base64.decodeBase64(authSplit[1].getBytes()));
            if (userpass != null) {
                String[] ar = userpass.split(":");
                if (ar.length > 0) {
                    String u = ar[0];
                    String p = "";
                    if (ar.length > 1) {
                        p = ar[1];
                    }
                    if (!allowAnonymous && "anonymous".equals(u)) {
                    } else {
                        cred = memeDB.getAuthentication().authenticate(u, p);

                        if (cred != null) {
                            log.debug("Authenticated as {} => {} via HTTP-AUTH", cred.getUsername(),
                                    cred.getToken());
                            addCredentialedCookie(response, cred);
                        }
                        return cred;
                    }
                }
            }
        }
        response.addHeader("WWW-Authenticate", " Basic realm=\"" + realm + "\"");
        sendNoAuthError(response, "You need a username and password");
        return null;
    }

    if (allowAnonymous) {
        if (allowAnonymousAsSa)
            return new SACredentials("anonymous", "", timeout);
        return new AnonCredentials("", timeout);
    }

    log.warn("Error authenticating");
    response.addHeader("WWW-Authenticate", " Basic realm=\"" + realm + "\"");
    sendNoAuthError(response, "You need a username and password");
    return null;
}

From source file:com.xpn.xwiki.user.impl.xwiki.MyPersistentLoginManager.java

/**
 * Remember a specific login using cookies.
 * // w  w w  .  jav  a  2s  .c om
 * @param request The servlet request.
 * @param response The servlet response.
 * @param username The username that's being remembered.
 * @param password The password that's being remembered.
 */
@Override
public void rememberLogin(HttpServletRequest request, HttpServletResponse response, String username,
        String password) {
    String protectedUsername = username;
    String protectedPassword = password;
    if (this.protection.equals(PROTECTION_ALL) || this.protection.equals(PROTECTION_ENCRYPTION)) {
        protectedUsername = encryptText(protectedUsername);
        protectedPassword = encryptText(protectedPassword);
        if (protectedUsername == null || protectedPassword == null) {
            LOGGER.error("ERROR!!");
            LOGGER.error("There was a problem encrypting the username or password!!");
            LOGGER.error("Remember Me function will be disabled!!");
            return;
        }
    }

    // Let's check if the cookies should be session cookies or persistent ones.
    boolean sessionCookie = !(isTrue(request.getParameter("j_rememberme")));
    String cookieDomain = getCookieDomain(request);

    // Create client cookies to remember the login information.

    // Username
    Cookie usernameCookie = new Cookie(getCookiePrefix() + COOKIE_USERNAME, protectedUsername);
    setupCookie(usernameCookie, sessionCookie, cookieDomain, response);

    // Password
    Cookie passwdCookie = new Cookie(getCookiePrefix() + COOKIE_PASSWORD, protectedPassword);
    setupCookie(passwdCookie, sessionCookie, cookieDomain, response);

    // Remember me
    Cookie rememberCookie = new Cookie(getCookiePrefix() + COOKIE_REMEMBERME, !sessionCookie + "");
    setupCookie(rememberCookie, sessionCookie, cookieDomain, response);

    if (this.protection.equals(PROTECTION_ALL) || this.protection.equals(PROTECTION_VALIDATION)) {
        String validationHash = getValidationHash(protectedUsername, protectedPassword, getClientIP(request));
        if (validationHash != null) {
            // Validation
            Cookie validationCookie = new Cookie(getCookiePrefix() + COOKIE_VALIDATION, validationHash);
            setupCookie(validationCookie, sessionCookie, cookieDomain, response);
        } else {
            if (LOGGER.isErrorEnabled()) {
                LOGGER.error("WARNING!!! WARNING!!!");
                LOGGER.error("PROTECTION=ALL or PROTECTION=VALIDATION was specified");
                LOGGER.error("but Validation Hash could NOT be generated");
                LOGGER.error("Validation has been disabled!!!!");
            }
        }
    }
    return;
}

From source file:com.techngage.smartbin.Controller.java

private void initializeRoutes() throws IOException {

    // Get all the available truck ids
    get(new Route("/truck") {
        @Override/*from w  ww . j a v a  2 s . com*/
        public Object handle(Request request, Response response) {
            List<Document> truckList = truckDAO.getTruckIds();
            String truckStr = "";
            String truckStrTmp = "";
            for (int i = 0; i < truckList.size(); i++) {
                truckStr = (String) truckList.get(i).get("truckid");
                if (i == truckList.size() - 1) {
                    truckStrTmp = truckStrTmp + truckStr;
                } else {
                    truckStrTmp = truckStrTmp + truckStr + ";";
                }
            }
            return truckStrTmp;
        }
    });

    // present signup form for smartbin app
    get(new Route("/unassign") {
        @Override
        public Object handle(Request request, Response response) {
            // Unassign route to truck.
            int routeId = Integer.parseInt(request.queryParams("routeid"));
            String truckId = request.queryParams("truckid");
            String status = routeDAO.unassignRoute(truckId, routeId);
            truckDAO.updateTruckAsUnAssigned(truckId, routeDAO.checkRouteAssigned(truckId));
            return status;
        }
    });

    // present signup form for smartbin app
    get(new Route("/assign") {
        @Override
        public Object handle(Request request, Response response) {
            // Assign route to truck.
            int routeId = Integer.parseInt(request.queryParams("routeid"));
            String truckId = request.queryParams("truckid");
            String status = routeDAO.assignRoute(truckId, routeId);
            truckDAO.updateTruckAsAssigned(truckId);
            return status;
        }
    });

    // insert location and coordinates, public api called from micro-controller
    post(new Route("/insert") {
        @Override
        public Object handle(Request request, Response response) {
            String cookie = getSessionCookie(request);
            String username = sessionDAO.findUserNameBySessionId(cookie);

            if (username == null) {
                System.out.println("You are not authorized");
                response.status(403);
            } else {
                // Insert route.
                String location = request.queryParams("location");
                String coordinates = request.queryParams("coordinates");
                boolean isDuplicate = locationDAO.checkDuplicateRoute(coordinates);
                if (location != null && coordinates != null && !isDuplicate) {
                    locationDAO.insertRoute(location, coordinates);
                }
            }
            return null;
        }
    });

    // handle the signup to smartbin web app
    post(new FreemarkerBasedRoute("/signup", "signup.ftl") {
        @Override
        protected void doHandle(Request request, Response response, Writer writer)
                throws IOException, TemplateException {
            String email = request.queryParams("email");
            String username = request.queryParams("username");
            String password = request.queryParams("password");
            String verify = request.queryParams("verify");

            HashMap<String, String> root = new HashMap<String, String>();
            root.put("username", StringEscapeUtils.escapeHtml4(username));
            root.put("email", StringEscapeUtils.escapeHtml4(email));

            if (validateSignup(username, password, verify, email, root)) {
                // good user
                System.out.println("Signup: Creating user with: " + username + " " + password);
                if (!userDAO.addUser(username, password, email)) {
                    // duplicate user
                    root.put("username_error", "Username already in use, Please choose another");
                    template.process(root, writer);
                } else {
                    // good user, let's start a session
                    String sessionID = sessionDAO.startSession(username);
                    System.out.println("Session ID is" + sessionID);

                    response.raw().addCookie(new Cookie("session", sessionID));
                    response.redirect("/dashboard");
                }
            } else {
                // bad signup
                System.out.println("User Registration did not validate");
                template.process(root, writer);
            }
        }
    });

    // present signup form for smartbin app
    get(new FreemarkerBasedRoute("/signup", "signup.ftl") {
        @Override
        protected void doHandle(Request request, Response response, Writer writer)
                throws IOException, TemplateException {

            SimpleHash root = new SimpleHash();

            // initialize values for the form.
            root.put("username", "");
            root.put("password", "");
            root.put("email", "");
            root.put("password_error", "");
            root.put("username_error", "");
            root.put("email_error", "");
            root.put("verify_error", "");

            template.process(root, writer);
        }
    });

    get(new FreemarkerBasedRoute("/dashboard", "dashboard.ftl") {
        @Override
        protected void doHandle(Request request, Response response, Writer writer)
                throws IOException, TemplateException {

            String cookie = getSessionCookie(request);
            String username = sessionDAO.findUserNameBySessionId(cookie);

            if (username == null) {
                System.out.println("dashboard() can't identify the user, redirecting to signup");
                response.redirect("/login");

            } else {
                SimpleHash root = new SimpleHash();
                int totRoutes = 3;
                List<Document> routes = routeDAO.getRoutes(totRoutes);
                root.put("username", username);
                root.put("names", routeDAO.getRoute());
                root.put("myroutes", routes);
                root.put("totallimitedroutes", totRoutes);
                root.put("totalescalatedroutes", routeDAO.getEscalatedRoutes().size());
                root.put("totalcompletedroutes", routeDAO.getCompletedRoutes().size());
                root.put("totalinprogressroutes", routeDAO.getEscalatedRoutes().size());

                List<Document> truckList = truckDAO.getTruckIds();
                /*String truckStr = "";
                String truckStrTmp = "";
                for(int i=0;i<truckList.size();i++){
                truckStr = (String)truckList.get(i).get("truckid");
                if(i == truckList.size()-1){
                    truckStrTmp = truckStrTmp + truckStr;
                } else {
                    truckStrTmp = truckStrTmp + truckStr + ";";
                }
                }*/
                root.put("trucklist", truckList);

                template.process(root, writer);
            }
        }
    });

    // present the login page
    get(new FreemarkerBasedRoute("/login", "login.ftl") {
        @Override
        protected void doHandle(Request request, Response response, Writer writer)
                throws IOException, TemplateException {
            SimpleHash root = new SimpleHash();

            root.put("username", "");
            root.put("login_error", "");

            template.process(root, writer);
        }
    });

    // process output coming from login form. On success redirect folks to the dashboard
    // on failure, just return an error and let them try again.
    post(new FreemarkerBasedRoute("/login", "login.ftl") {
        @Override
        protected void doHandle(Request request, Response response, Writer writer)
                throws IOException, TemplateException {

            String username = request.queryParams("username");
            String password = request.queryParams("password");

            System.out.println("Login: User submitted: " + username + "  " + password);

            Document user = userDAO.validateLogin(username, password);

            if (user != null) {

                // valid user, let's log them in
                String sessionID = sessionDAO.startSession(user.get("_id").toString());

                if (sessionID == null) {
                    response.redirect("/internal_error");
                } else {
                    // set the cookie for the user's browser
                    response.raw().addCookie(new Cookie("session", sessionID));

                    response.redirect("/dashboard");
                }
            } else {
                SimpleHash root = new SimpleHash();

                root.put("username", StringEscapeUtils.escapeHtml4(username));
                root.put("password", "");
                root.put("login_error", "Invalid Login");
                template.process(root, writer);
            }
        }
    });

    // allows the user to logout of the smartbin app
    get(new FreemarkerBasedRoute("/logout", "signup.ftl") {
        @Override
        protected void doHandle(Request request, Response response, Writer writer)
                throws IOException, TemplateException {

            String sessionID = getSessionCookie(request);
            if (sessionID == null) {
                // no session to end
                response.redirect("/login");
            } else {
                // deletes from session table
                sessionDAO.endSession(sessionID);

                // this should delete the cookie
                Cookie c = getSessionCookieActual(request);
                c.setMaxAge(0);

                response.raw().addCookie(c);

                response.redirect("/login");
            }
        }
    });

    // used to process internal errors
    get(new FreemarkerBasedRoute("/internal_error", "error_template.ftl") {
        @Override
        protected void doHandle(Request request, Response response, Writer writer)
                throws IOException, TemplateException {
            SimpleHash root = new SimpleHash();

            root.put("error", "System has encountered an error.");
            template.process(root, writer);
        }
    });
}

From source file:edu.indiana.d2i.sloan.ui.LoginSuccessAction.java

/**
 * retrieve access token, refresh token and user info from WS IS
 *///from   w  w w.  j a  v a  2 s .  c om
@Override
public String execute() {
    String token = (String) ActionContext.getContext().getSession().get(Constants.SESSION_TOKEN);
    if (token == null) {
        try {
            OAuthAuthzResponse authzResponse = OAuthAuthzResponse.oauthCodeAuthzResponse(getServletRequest());
            String authzCode = authzResponse.getCode();
            if (authzCode == null) {
                logger.error("OAuth2 provider returned empty authorization code.");
                addActionError("OAuth2 provider returned empty authorization code.");
                return ERROR;
            }

            // set SSL
            if (!disableSSL())
                return ERROR;

            // get access token
            String webAppContext = getServerContext();
            String redirectUrl = webAppContext + "/LoginSuccessAction";
            OAuthClientRequest tokenRequest = OAuthClientRequest
                    .tokenLocation(PortalConfiguration.getOAuth2TokenEndpoint())
                    .setGrantType(GrantType.AUTHORIZATION_CODE)
                    .setClientId(PortalConfiguration.getOAuth2ClientID())
                    .setClientSecret(PortalConfiguration.getOAuth2ClientSecrete()).setRedirectURI(redirectUrl)
                    .setCode(authzCode).buildBodyMessage();

            OAuth2Client tokenClient = new OAuth2Client(new URLConnectionClient());
            OAuthClientResponse tokenResponse = tokenClient.accessToken(tokenRequest);
            String accessToken = tokenResponse.getParam(Constants.OAUTH2_ACCESS_TOKEN);
            String refreshToken = tokenResponse.getParam(Constants.OAUTH2_REFRESH_TOKEN);
            Long expireInSec = Long.valueOf(tokenResponse.getParam(Constants.OAUTH2_EXPIRE));

            // get user info

            // token relative stuffs
            session.put(Constants.SESSION_TOKEN, accessToken);
            session.put(Constants.SESSION_REFRESH_TOKEN, refreshToken);
            session.put(Constants.SESSION_TOKEN_EXPIRE_SEC, expireInSec);

            if (logger.isDebugEnabled()) {
                logger.debug("Access Token from Oauth2:" + accessToken);
            }

            // request userinfo
            OAuthClientRequest userInfoRequest = OAuthUserInfoRequest
                    .userInfoLocation(PortalConfiguration.getOAuth2UserinfoEndpoint())
                    .setClientId(PortalConfiguration.getOAuth2ClientID())
                    .setClientSecret(PortalConfiguration.getOAuth2ClientSecrete()).setAccessToken(accessToken)
                    .buildBodyMessage();
            OAuth2Client userInfoClient = new OAuth2Client(new URLConnectionClient());
            OAuthClientResponse userInfoResponse = userInfoClient.userInfo(userInfoRequest);
            String userName = userInfoResponse.getParam("authorized_user");

            if (userName == null || "".equals(userName)) {
                String errMsg = "Cannot obtain username from Oauth2";
                logger.error(errMsg);
                addActionError(errMsg);
                return ERROR;
            }

            if (logger.isDebugEnabled()) {
                logger.debug("Username from Oauth2:" + userName);
            }

            // user name
            session.put(Constants.SESSION_USERNAME, userName);

            // session cookie
            httpResponse.addCookie(new Cookie(Constants.SESSION_EXIST_BEFORE, "true")); // username
            session.put(Constants.SESSION_EXIST_BEFORE, new Boolean(false));

            return SUCCESS;
        } catch (OAuthProblemException e) {
            logger.error(e.getError(), e);
            addActionError(e.getError());
            return ERROR;
        } catch (OAuthSystemException e) {
            logger.error(e.getMessage(), e);
            addActionError(e.getMessage());
            return ERROR;
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
            addActionError(e.getMessage());
            return ERROR;
        }
    }
    return SUCCESS;
}

From source file:eu.supersede.fe.security.SecurityConfiguration.java

private Filter csrfHeaderFilter() {
    return new OncePerRequestFilter() {
        @Override/*from  w  w w . j  a v  a 2  s .c o m*/
        protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
                FilterChain filterChain) throws ServletException, IOException {
            CsrfToken csrf = (CsrfToken) request.getAttribute(CsrfToken.class.getName());

            if (csrf != null) {
                Cookie cookie = WebUtils.getCookie(request, "XSRF-TOKEN");
                String token = csrf.getToken();

                if (cookie == null || token != null && !token.equals(cookie.getValue())) {
                    cookie = new Cookie("XSRF-TOKEN", token);
                    cookie.setPath("/");
                    response.addCookie(cookie);
                }
            }

            try {
                filterChain.doFilter(request, response);
            } catch (IOException e) {
                if (!csrf_error) {
                    log.warn("Unable to apply the CSRF filter. This message will not be displayed again");
                } else {
                    csrf_error = true;
                }
            }
        }
    };
}

From source file:gr.abiss.calipso.wicket.HeaderPanel.java

public HeaderPanel() {
    super("header");

    final User user = getPrincipal();
    final List<Space> spaces = user != null ? new ArrayList<Space>(user.getSpaces()) : new ArrayList<Space>();

    boolean hideLogin = BooleanUtils.toBoolean(getCalipso().loadConfig("calipso.hideLoginLink"));
    boolean hideRegister = BooleanUtils.toBoolean(getCalipso().loadConfig("calipso.hideRegisterLink"));
    // manage single space
    if (spaces.size() == 1) {
        setCurrentSpace(spaces.get(0));//ww  w.  j  ava2 s . c om
    }
    final Space space = getCurrentSpace();
    Component link = null;
    if (getPrincipal().isAnonymous()) {
        ExternalLink externalLink = new ExternalLink("dashboard", "/");
        externalLink.setContextRelative(true);
        link = externalLink;
    } else {
        link = new Link("dashboard") {
            public void onClick() {
                setCurrentSpace(null);
                setResponsePage(DashboardPage.class);
            }
        };
    }
    add(link);

    if (space == null) {

        // add(new Label("space", "").setVisible(false));// 1
        // add(new Label("new", "").setVisible(false));// 2
        add(new Link("search") {// 3
            public void onClick() {
                setResponsePage(ItemSearchFormPage.class);
            }
        }.setVisible(user != null && user.getSpaceCount() > 0 && !user.isAnonymous()));
    } else {
        /*
         * add(new Link("space") {
         * 
         * @Override public void onClick() {
         * setResponsePage(SpacePage.class); } }.add(new Label("space",
         * space.getName())));
         */
        // add(new WebMarkupContainer("space").add(new Label("space",
        // space.getName())));

        // In case that User opens an Item direct from e-mail notification
        // link
        // and has no access to this Item
        /*
         * try { if (user.getPermittedTransitions(space, State.NEW).size() >
         * 0) { add(new Link("new") { public void onClick() {
         * setResponsePage(ItemFormPage.class); } }); } else { add(new
         * WebMarkupContainer("new").setVisible(false)); } } catch
         * (Exception e) { logger.error("user.getPermittedTransitions :: " +
         * e.getMessage()); add(new
         * WebMarkupContainer("new").setVisible(false)); }
         */
        add(new Link("search") {
            public void onClick() {
                // if search then we user global search
                setCurrentSpace(null);
                setResponsePage(ItemSearchFormPage.class);
            }
        }.setVisible(user.getSpaceCount() > 0 && !user.isAnonymous()));
    }

    if (user == null || user.getId() == 0) {
        add(new WebMarkupContainer("options").setVisible(false));
        add(new WebMarkupContainer("logout").setVisible(false));
        add(new Link("login") {
            public void onClick() {
                setResponsePage(LoginPage.class);
            }
        }.setVisible(!hideLogin));
        add(new Link("register") {
            public void onClick() {
                setResponsePage(RegisterAnonymousUserFormPage.class);
            }
        }.setVisible(!hideRegister));
        add(new WebMarkupContainer("user").setVisible(false));
    } else {
        add(new Link("options") {
            public void onClick() {
                // when options clicked then we go to menu that space
                // doesn't have meaning
                setCurrentSpace(null);
                setResponsePage(OptionsPage.class);
            }
        });
        add(new Link("logout") {
            public void onClick() {
                Cookie cookie = new Cookie("calipsoService", "");
                String path = ((WebRequest) getRequest()).getContextPath();
                cookie.setPath(path);
                ((WebResponse) getResponse()).clearCookie(cookie);
                getSession().invalidate();
                logger.debug("invalidated session and cleared cookie");
                // is acegi - cas being used ?
                String logoutUrl = ((CalipsoApplication) getApplication()).getCasLogoutUrl();
                if (logoutUrl != null) {
                    logger.debug(
                            "cas authentication being used, clearing security context and redirecting to cas logout page");
                    SecurityContextHolder.clearContext();
                    // have to use stateless page reference because session
                    // is killed
                    setResponsePage(CasLogoutPage.class);
                } else {
                    setResponsePage(LogoutPage.class, new PageParameters("locale=" + user.getLocale()));
                }
            }
        });
        add(new WebMarkupContainer("login").setVisible(false));
        // issue
        add(new WebMarkupContainer("register").setVisible(false));

        add(new Link("user") {
            public void onClick() {
                setResponsePage(new UserViewPage(user));
            }
        }.add(new Label("user", user.getDisplayValue()).setRenderBodyOnly(true)));
    }
}

From source file:com.salesmanager.core.util.LocaleUtil.java

public static void setLocaleForRequest(HttpServletRequest request, HttpServletResponse response,
        ActionContext ctx, MerchantStore store) throws Exception {

    /**/*from   w  ww .  j  a v  a2  s . co m*/
     * LOCALE
     */

    Map sessions = ctx.getSession();

    if (ctx == null) {
        throw new Exception("This request was not made inside Struts request, ActionContext is null");
    }

    Locale locale = null;

    // check in http request
    String req_locale = (String) request.getParameter("request_locale");
    if (!StringUtils.isBlank(req_locale)) {

        String l = null;
        String c = null;

        if (req_locale.length() == 2) {//assume it is the language
            l = req_locale;
            c = CountryUtil.getCountryIsoCodeById(store.getCountry());
        }

        if (req_locale.length() == 5) {

            try {
                l = req_locale.substring(0, 2);
                c = req_locale.substring(3);
            } catch (Exception e) {
                log.warn("Invalid locale format " + req_locale);
                l = null;
                c = null;
            }

        }

        if (l != null && c != null) {

            String storeLang = null;
            Map languages = store.getGetSupportedLanguages();
            if (languages != null && languages.size() > 0) {
                Iterator i = languages.keySet().iterator();
                while (i.hasNext()) {
                    Integer langKey = (Integer) i.next();
                    Language lang = (Language) languages.get(langKey);
                    if (lang.getCode().equals(l)) {
                        storeLang = l;
                        break;
                    }
                }
            }

            if (storeLang == null) {
                l = store.getDefaultLang();
                if (StringUtils.isBlank(l)) {
                    l = LanguageUtil.getDefaultLanguage();
                }
            }

            locale = new Locale(l, c);
            if (StringUtils.isBlank(locale.getLanguage()) || StringUtils.isBlank(locale.getCountry())) {
                log.error("Language or Country is not set in the new locale " + req_locale);
                return;
            }
            sessions.put("WW_TRANS_I18N_LOCALE", locale);

        }
    }

    locale = (Locale) sessions.get("WW_TRANS_I18N_LOCALE");
    request.getSession().setAttribute("WW_TRANS_I18N_LOCALE", locale);

    if (locale == null) {

        String c = CountryUtil.getCountryIsoCodeById(store.getCountry());
        String lang = store.getDefaultLang();
        if (!StringUtils.isBlank(c) && !StringUtils.isBlank(lang)) {
            locale = new Locale(lang, c);
        } else {
            locale = LocaleUtil.getDefaultLocale();
            String langs = store.getSupportedlanguages();
            if (!StringUtils.isBlank(langs)) {
                Map languages = store.getGetSupportedLanguages();
                String defaultLang = locale.getLanguage();
                if (languages != null && languages.size() > 0) {
                    Iterator i = languages.keySet().iterator();
                    String storeLang = "";
                    while (i.hasNext()) {
                        Integer langKey = (Integer) i.next();
                        Language l = (Language) languages.get(langKey);
                        if (l.getCode().equals(defaultLang)) {
                            storeLang = defaultLang;
                            break;
                        }
                    }
                    if (!storeLang.equals(defaultLang)) {
                        defaultLang = storeLang;
                    }
                }

                if (!StringUtils.isBlank(defaultLang) && !StringUtils.isBlank(c)) {
                    locale = new Locale(defaultLang, c);
                }

            }
        }

        sessions.put("WW_TRANS_I18N_LOCALE", locale);
    }

    if (locale != null) {
        LabelUtil label = LabelUtil.getInstance();
        label.setLocale(locale);
        String lang = label.getText("label.language." + locale.getLanguage());
        request.setAttribute("LANGUAGE", lang);
    }

    if (store.getLanguages() == null || store.getLanguages().size() == 0) {

        // languages
        if (!StringUtils.isBlank(store.getSupportedlanguages())) {
            List languages = new ArrayList();
            List langs = LanguageUtil.parseLanguages(store.getSupportedlanguages());
            for (Object o : langs) {
                String lang = (String) o;
                Language l = LanguageUtil.getLanguageByCode(lang);
                if (l != null) {
                    l.setLocale(locale, store.getCurrency());
                    languages.add(l);
                }
            }
            store.setLanguages(languages);
        }
    }

    request.setAttribute("LOCALE", locale);
    Cookie c = new Cookie("LOCALE", locale.getLanguage() + "_" + locale.getCountry());
    c.setPath("/");
    c.setMaxAge(2 * 24 * 24);
    response.addCookie(c);

}