Example usage for javax.servlet.http Cookie setMaxAge

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

Introduction

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

Prototype

public void setMaxAge(int expiry) 

Source Link

Document

Sets the maximum age in seconds for this Cookie.

Usage

From source file:cn.knet.showcase.demos.servletproxy.ProxyServlet.java

/** Copy cookie from the proxy to the servlet client.
 *  Replaces cookie path to local path and renames cookie to avoid collisions.
 *///  ww  w.  jav a  2  s  . c  om
protected void copyProxyCookie(HttpServletRequest servletRequest, HttpServletResponse servletResponse,
        Header header) {
    List<HttpCookie> cookies = HttpCookie.parse(header.getValue());
    String path = servletRequest.getContextPath(); // path starts with / or is empty string
    path += servletRequest.getServletPath(); // servlet path starts with / or is empty string

    for (HttpCookie cookie : cookies) {
        //set cookie name prefixed w/ a proxy value so it won't collide w/ other cookies
        String proxyCookieName = getCookieNamePrefix() + cookie.getName();
        Cookie servletCookie = new Cookie(proxyCookieName, cookie.getValue());
        servletCookie.setComment(cookie.getComment());
        servletCookie.setMaxAge((int) cookie.getMaxAge());
        servletCookie.setPath(path); //set to the path of the proxy servlet
        // don't set cookie domain
        servletCookie.setSecure(cookie.getSecure());
        servletCookie.setVersion(cookie.getVersion());
        servletResponse.addCookie(servletCookie);
    }
}

From source file:es.pode.soporte.seguridad.openId.ui.openid.OpenIDAuthenticationProcessingFilter.java

/** 
* Invalida la cookie AUTENTICADO//  ww  w . j  av  a 2s .  c o  m
* @param response
* @param request
*/
private void invalidateCookieAutenticado(HttpServletResponse response) throws IOException {

    Cookie cookieAutenticado = new Cookie("AUTENTICADO", "");
    cookieAutenticado.setPath("/");
    cookieAutenticado.setMaxAge(0);
    response.addCookie(cookieAutenticado);

}

From source file:org.gss_project.gss.server.Login.java

@Override
public void service(HttpServletRequest request, HttpServletResponse response) throws IOException {
    // Fetch the next URL to display, if any.
    String nextUrl = request.getParameter(NEXT_URL_PARAM);
    // Fetch the supplied nonce, if any.
    String nonce = request.getParameter(NONCE_PARAM);
    String[] attrs = new String[] { "REMOTE_USER", "HTTP_SHIB_INETORGPERSON_DISPLAYNAME",
            "HTTP_SHIB_INETORGPERSON_GIVENNAME", "HTTP_SHIB_PERSON_COMMONNAME", "HTTP_SHIB_PERSON_SURNAME",
            "HTTP_SHIB_INETORGPERSON_MAIL", "HTTP_SHIB_EP_UNSCOPEDAFFILIATION", "HTTP_PERSISTENT_ID",
            "HTTP_SHIB_HOMEORGANIZATION" };
    StringBuilder buf = new StringBuilder("Shibboleth Attributes\n");
    for (String attr : attrs)
        buf.append(attr + ": ").append(request.getAttribute(attr)).append('\n');
    logger.info(buf);//from   w  ww  .  j  av  a  2s  . c om
    if (logger.isDebugEnabled()) {
        buf = new StringBuilder("Shibboleth Attributes as bytes\n");
        for (String attr : attrs)
            if (request.getAttribute(attr) != null)
                buf.append(attr + ": ")
                        .append(getHexString(request.getAttribute(attr).toString().getBytes("UTF-8")))
                        .append('\n');
        logger.debug(buf);
    }
    User user = null;
    response.setContentType("text/html");
    Object usernameAttr = request.getAttribute("REMOTE_USER");
    Object nameAttr = request.getAttribute("HTTP_SHIB_INETORGPERSON_DISPLAYNAME");
    Object givennameAttr = request.getAttribute("HTTP_SHIB_INETORGPERSON_GIVENNAME"); // Multi-valued
    Object cnAttr = request.getAttribute("HTTP_SHIB_PERSON_COMMONNAME"); // Multi-valued
    Object snAttr = request.getAttribute("HTTP_SHIB_PERSON_SURNAME"); // Multi-valued
    Object mailAttr = request.getAttribute("HTTP_SHIB_INETORGPERSON_MAIL"); // Multi-valued
    Object persistentIdAttr = request.getAttribute("HTTP_PERSISTENT_ID");
    Object homeOrganizationAttr = request.getAttribute("HTTP_SHIB_HOMEORGANIZATION");
    // Use a configured test username if found, as a shortcut for development deployments.
    String gwtServer = null;
    if (getConfiguration().getString("testUsername") != null) {
        usernameAttr = getConfiguration().getString("testUsername");
        // Fetch the GWT code server URL, if any.
        gwtServer = request.getParameter(GWT_SERVER_PARAM);
    }
    if (usernameAttr == null) {
        String authErrorUrl = "authenticationError.jsp";
        authErrorUrl += "?name=" + (nameAttr == null ? "-" : nameAttr.toString());
        authErrorUrl += "&givenname=" + (givennameAttr == null ? "-" : givennameAttr.toString());
        authErrorUrl += "&sn=" + (snAttr == null ? "-" : snAttr.toString());
        authErrorUrl += "&cn=" + (cnAttr == null ? "-" : cnAttr.toString());
        authErrorUrl += "&mail=" + (mailAttr == null ? "-" : mailAttr.toString());
        authErrorUrl += "&homeOrg=" + (homeOrganizationAttr == null ? "-" : homeOrganizationAttr.toString());
        response.sendRedirect(authErrorUrl);
        return;
    }
    String username = decodeAttribute(usernameAttr);
    String name;
    if (nameAttr != null && !nameAttr.toString().isEmpty())
        name = decodeAttribute(nameAttr);
    else if (cnAttr != null && !cnAttr.toString().isEmpty()) {
        name = decodeAttribute(cnAttr);
        if (name.indexOf(';') != -1)
            name = name.substring(0, name.indexOf(';'));
    } else if (givennameAttr != null && snAttr != null && !givennameAttr.toString().isEmpty()
            && !snAttr.toString().isEmpty()) {
        String givenname = decodeAttribute(givennameAttr);
        if (givenname.indexOf(';') != -1)
            givenname = givenname.substring(0, givenname.indexOf(';'));
        String sn = decodeAttribute(snAttr);
        if (sn.indexOf(';') != -1)
            sn = sn.substring(0, sn.indexOf(';'));
        name = givenname + ' ' + sn;
    } else if (givennameAttr == null && snAttr != null && !snAttr.toString().isEmpty()) {
        name = decodeAttribute(snAttr);
        if (name.indexOf(';') != -1)
            name = name.substring(0, name.indexOf(';'));
    } else
        name = username;
    String mail = mailAttr != null ? mailAttr.toString() : username;
    if (mail.indexOf(';') != -1)
        mail = mail.substring(0, mail.indexOf(';'));
    String persistentId = persistentIdAttr != null ? persistentIdAttr.toString() : "";
    String idp = "";
    String idpid = "";
    if (!persistentId.isEmpty()) {
        int bang = persistentId.indexOf('!');
        if (bang > -1) {
            idp = persistentId.substring(0, bang);
            idpid = persistentId.substring(bang + 1);
        }
    }
    String homeOrganization = homeOrganizationAttr != null ? decodeAttribute(homeOrganizationAttr.toString())
            : "";
    try {
        user = getService().findUser(username);
        if (user == null)
            user = getService().createUser(username, name, mail, idp, idpid, homeOrganization);
        if (!user.isActive()) {
            logger.info("Disabled user " + username + " tried to login.");
            response.sendError(HttpServletResponse.SC_FORBIDDEN, "This account is disabled");
            return;
        }
        if (!user.hasAcceptedPolicy()) {
            String policyUrl = "policy.jsp";
            if (request.getQueryString() != null)
                policyUrl += "?user=" + username + "&" + request.getQueryString();
            response.sendRedirect(policyUrl);
            return;
        }
        user.setName(name);
        user.setEmail(mail);
        user.setIdentityProvider(idp);
        user.setIdentityProviderId(idpid);
        user.setHomeOrganization(homeOrganization);

        UserLogin userLogin = new UserLogin();
        userLogin.setLoginDate(new Date());
        userLogin.setUser(user);
        if (user.getAuthToken() == null)
            user = getService().updateUserToken(user.getId());
        // Set WebDAV password to token if it's never been set.
        if (user.getWebDAVPassword() == null || user.getWebDAVPassword().length() == 0) {
            String tokenEncoded = new String(Base64.encodeBase64(user.getAuthToken()), "US-ASCII");
            user.setWebDAVPassword(tokenEncoded);
        }
        // Set the default user class if none was set.
        if (user.getUserClass() == null)
            user.setUserClass(getService().getUserClasses().get(0));
        getService().updateUser(user);
        getService().addUserLogin(userLogin);
    } catch (RpcException e) {
        String error = "An error occurred while communicating with the service";
        logger.error(error, e);
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, error);
        return;
    } catch (DuplicateNameException e) {
        String error = "User with username " + username + " already exists";
        logger.error(error, e);
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, error);
        return;
    } catch (ObjectNotFoundException e) {
        String error = "No username was provided";
        logger.error(error, e);
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, error);
        return;
    }
    String tokenEncoded = new String(Base64.encodeBase64(user.getAuthToken()), "US-ASCII");
    String userEncoded = URLEncoder.encode(user.getUsername(), "US-ASCII");
    if (logger.isDebugEnabled())
        logger.debug("user: " + userEncoded + " token: " + tokenEncoded);
    if (nextUrl != null && !nextUrl.isEmpty()) {
        URI next;
        if (gwtServer != null)
            nextUrl += '?' + GWT_SERVER_PARAM + '=' + gwtServer;

        if (nextUrl.indexOf(FileHeader.PATH_FILES) != -1) {
            int pathIndex = nextUrl.indexOf(FileHeader.PATH_FILES) + FileHeader.PATH_FILES.length() + 1;
            String path = nextUrl.substring(pathIndex);
            path = URLEncoder.encode(path, "UTF-8");
            nextUrl = nextUrl.substring(0, pathIndex) + path;
        }
        try {
            next = new URI(nextUrl);
        } catch (URISyntaxException e) {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getMessage());
            return;
        }
        if ("x-gr-ebs-igss".equalsIgnoreCase(next.getScheme()))
            nextUrl += "?u=" + userEncoded + "&t=" + tokenEncoded;
        else {
            String domain = next.getHost();
            String path = getServletContext().getContextPath() + '/';
            Cookie cookie = new Cookie(AUTH_COOKIE, userEncoded + COOKIE_SEPARATOR + tokenEncoded);
            cookie.setMaxAge(-1);
            cookie.setDomain(domain);
            cookie.setPath(path);
            response.addCookie(cookie);
            cookie = new Cookie(WEBDAV_COOKIE, user.getWebDAVPassword());
            cookie.setMaxAge(-1);
            cookie.setDomain(domain);
            cookie.setPath(path);
            response.addCookie(cookie);
        }
        response.sendRedirect(nextUrl);
    } else if (nonce != null) {
        nonce = URLEncoder.encode(nonce, "US-ASCII");
        Nonce n = null;
        try {
            if (logger.isDebugEnabled())
                logger.debug("user: " + user.getId() + " nonce: " + nonce);
            n = getService().getNonce(nonce, user.getId());
        } catch (ObjectNotFoundException e) {
            PrintWriter out = response.getWriter();
            out.println("<HTML>");
            out.println("<HEAD><TITLE>" + getServiceName() + " Authentication</TITLE>"
                    + "<LINK TYPE='text/css' REL='stylesheet' HREF='gss.css'></HEAD>");
            out.println("<BODY><CENTER><P>");
            out.println("The supplied nonce could not be found!");
            out.println("</CENTER></BODY></HTML>");
            return;
        } catch (RpcException e) {
            String error = "An error occurred while communicating with the service";
            logger.error(error, e);
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, error);
            return;
        }
        try {
            getService().activateUserNonce(user.getId(), nonce, n.getNonceExpiryDate());
        } catch (ObjectNotFoundException e) {
            String error = "Unable to find user";
            logger.error(error, e);
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, error);
            return;
        } catch (RpcException e) {
            String error = "An error occurred while communicating with the service";
            logger.error(error, e);
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, error);
            return;
        }
        try {
            getService().removeNonce(n.getId());
        } catch (ObjectNotFoundException e) {
            logger.info("Nonce already removed!", e);
        } catch (RpcException e) {
            logger.warn("Could not remove nonce from data store", e);
        }
        PrintWriter out = response.getWriter();
        out.println("<HTML>");
        out.println("<HEAD><TITLE>" + getServiceName() + " Authentication</TITLE>"
                + "<LINK TYPE='text/css' REL='stylesheet' HREF='gss.css'></HEAD>");
        out.println("<BODY><CENTER><P>");
        out.println("You can now close this browser window and return to your application.");
        out.println("</CENTER></BODY></HTML>");
    } else {
        PrintWriter out = response.getWriter();
        out.println("<HTML>");
        out.println("<HEAD><TITLE>" + getServiceName() + " Authentication</TITLE>"
                + "<LINK TYPE='text/css' REL='stylesheet' HREF='gss.css'></HEAD>");
        out.println("<BODY><CENTER><P>");
        out.println("Name: " + user.getName() + "<BR>");
        out.println("E-mail: " + user.getEmail() + "<BR><P>");
        out.println("Username: " + user.getUsername() + "<BR>");
        out.println("Athentication token: " + tokenEncoded + "<BR>");
        out.println("</CENTER></BODY></HTML>");
    }
}

From source file:com.netspective.sparx.security.HttpLoginManager.java

public void logout(HttpServletValueContext vc) {
    vc.getProject().getScrollStates().removeActiveState(vc);

    if (isAllowRememberUserId()) {
        Cookie cookie = new Cookie(getRememberUserIdCookieName(), "");
        cookie.setPath(getRememberPasswordCookiePath(vc));
        cookie.setMaxAge(-1);
        vc.getHttpResponse().addCookie(cookie);
        cookie = new Cookie(getRememberPasswordCookieName(), "");
        cookie.setPath(getRememberPasswordCookiePath(vc));
        cookie.setMaxAge(-1);//from  w  ww.  ja v  a2  s.c  o m
        vc.getHttpResponse().addCookie(cookie);
    }

    final HttpServletRequest req = vc.getHttpRequest();
    final MutableAuthenticatedUser user = (MutableAuthenticatedUser) getAuthenticatedUser(req);
    final HttpSession session = req.getSession();
    if (user != null) {
        registerLogout(vc, user);
        session.removeAttribute(getAuthenticatedUserSessionAttrName());
    }
    session.invalidate();
}

From source file:de.innovationgate.wga.server.api.Call.java

/**
 * Creates a new completely initialized HTTP cookie, which is not yet assigned to the call.
 * Use {@link #addCookie(Cookie)} to do so and send it to the client.
 * The cookie is initialized with path (the OpenWGA context path), type/maxage (transient),
 * domain (either request host or host from configured server base url) and security
 * flag (true if the current call is HTTPS).
 * @param name Name of the cookie//from  www  . j ava 2 s .c om
 * @param value Value of the cookie
 * @return
 * @throws WGException
 */
public Cookie createCookie(String name, String value) throws WGException {

    URLBuilder baseURL = _wga.urlBuilder(_wga.server().getBaseURL());
    URLBuilder requestURL = _wga.urlBuilder(getURL());

    Cookie c = new Cookie();
    c.setName(name);
    c.setValue(value);
    c.setMaxAge(-1);
    c.setPath(baseURL.build(false));
    if (_wga.isRequestAvailable()) {
        c.setDomain(requestURL.getHost());
    } else {
        c.setDomain(baseURL.getHost());
    }
    c.setSecure(requestURL.getProtocol().equals("https"));

    return c;

}

From source file:com.netspective.sparx.security.HttpLoginManager.java

public void login(HttpServletValueContext vc, MutableAuthenticatedUser user, boolean rememberUserId) {
    vc.getHttpRequest().getSession().setAttribute(getAuthenticatedUserSessionAttrName(), user);

    if (isAllowRememberUserId() && rememberUserId) {
        Cookie cookie = new Cookie(getRememberUserIdCookieName(), user.getUserId().toString());
        cookie.setPath(getRememberPasswordCookiePath(vc));
        cookie.setMaxAge(getRememberUserIdCookieMaxAge());
        vc.getHttpResponse().addCookie(cookie);
        cookie = new Cookie(getRememberPasswordCookieName(), user.getEncryptedPassword());
        cookie.setMaxAge(getRememberUserIdCookieMaxAge());
        cookie.setPath(getRememberPasswordCookiePath(vc));
        vc.getHttpResponse().addCookie(cookie);
    }/*from   ww w  . j  a v  a  2  s  . c o  m*/

    registerLogin(vc, user);
}

From source file:com.yahoo.yos.YahooFilter.java

public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
        throws IOException, ServletException {
    HttpServletRequest request = (HttpServletRequest) servletRequest;
    HttpServletResponse response = (HttpServletResponse) servletResponse;

    String yap_appid = getParam(request, "yap_appid");
    SESSION_TYPE sessionType;//from w  ww  . j  a v a2  s.co  m
    if ("POST".equals(request.getMethod()) && yap_appid != null && yap_appid.length() > 0) {
        sessionType = SESSION_TYPE.YAHOO_YAP_SESSION_TYPE;
    } else if (cookieExists(request.getCookies(), "yosdk_at")) {
        sessionType = SESSION_TYPE.YAHOO_OAUTH_AT_SESSION_TYPE;
    } else if (cookieExists(request.getCookies(), "yosdk_rt")) {
        sessionType = SESSION_TYPE.YAHOO_OAUTH_RT_SESSION_TYPE;
    } else {
        sessionType = null;
    }

    if (logger.isDebugEnabled()) {
        logger.debug("sessionType: {}", sessionType);
    }

    OAuthAccessor accessor = new OAuthAccessor(consumer);

    if (sessionType == null) {
        if (redirect) {
            if (logger.isDebugEnabled()) {
                logger.debug("redirecting user to yahoo acquire access token");
            }
            redirectForAuthorization(accessor, request, response);
            return;
        } else {
            if (logger.isDebugEnabled()) {
                logger.debug("inserting YahooSession suitable for 2-legged oauth calls into request attribute");
            }
            String appId = oauthConfig.getProperty("yos.appid");
            request.setAttribute("yahooSession", new YahooSession(client, consumer, null, appId));
        }
    } else if (sessionType == SESSION_TYPE.YAHOO_YAP_SESSION_TYPE) {
        if (logger.isDebugEnabled()) {
            logger.debug("inserting YahooSession suitable for 2-legged oauth calls into request attribute");
        }
        if (consumer.consumerKey == null
                || !consumer.consumerKey.equals(getParam(request, "yap_consumer_key"))) {
            logger.error("Consumer key from YAP does not match config.");
            clearSession(request, response);
            if (redirect) {
                redirectForAuthorization(accessor, request, response);
                return;
            }
        }
        try {
            OAuthSignatureMethod method = OAuthSignatureMethod.newMethod("HMAC-SHA1", accessor);
            OAuthMessage msg = OAuthServlet.getMessage(request, null);
            method.validate(msg);
        } catch (OAuthProblemException ex) {
            logger.error("Signature from YAP failed.", ex);
            clearSession(request, response);
            if (redirect) {
                redirectForAuthorization(accessor, request, response);
                return;
            }
        } catch (Exception ex) {
            throw new ServletException(ex);
        }
        AccessToken at = new AccessToken();
        at.setKey(getParam(request, "yap_viewer_access_token"));
        at.setSecret(getParam(request, "yap_viewer_access_token_secret"));
        at.setGuid(getParam(request, "yap_viewer_guid"));
        at.setOwner(getParam(request, "yap_owner_guid"));
        at.setTokenExpires(-1);
        String appId = getParam(request, "yap_appid");
        YahooSession yahooSession = new YahooSession(client, consumer, at, appId);
        request.setAttribute("yahooSession", yahooSession);
    } else if (sessionType == SESSION_TYPE.YAHOO_OAUTH_AT_SESSION_TYPE) {
        long now = System.currentTimeMillis() / 1000;
        try {
            AccessToken accessToken = new AccessToken(cookie(request.getCookies(), "yosdk_at"));
            if (consumer.consumerKey == null || !consumer.consumerKey.equals(accessToken.getConsumer())) {
                logger.error(
                        "Consumer key for token does not match the defined Consumer Key.  The Consumer Key has probably changed since the user last authorized the application.");
                clearSession(request, response);
                if (redirect) {
                    redirectForAuthorization(accessor, request, response);
                    return;
                }
            }
            if (accessToken.getTokenExpires() >= 0 && logger.isDebugEnabled()) {
                logger.debug("AT Expires in: {}", (accessToken.getTokenExpires() - now));
            }
            if (accessToken.getTokenExpires() >= 0 && (accessToken.getTokenExpires() - now) < 30) {
                try {
                    accessTokenExpired(accessor, request, response, accessToken, filterChain);
                } catch (OAuthException ex) {
                    if (ex instanceof OAuthProblemException) {
                        OAuthProblemException oape = (OAuthProblemException) ex;
                        String s = oape.getProblem() + oape.getParameters();
                        throw new ServletException(s, ex);
                    }
                    throw new ServletException(ex);
                } catch (URISyntaxException ex) {
                    throw new ServletException(ex);
                }
                return;
            } else {
                String appId = oauthConfig.getProperty("yos.appid");
                YahooSession yahooSession = new YahooSession(client, consumer, accessToken, appId);
                request.setAttribute("yahooSession", yahooSession);
            }
        } catch (JSONException e) {
            throw new ServletException(e);
        }
    } else if (sessionType == SESSION_TYPE.YAHOO_OAUTH_RT_SESSION_TYPE) {
        try {
            RequestToken rt = new RequestToken(cookie(request.getCookies(), "yosdk_rt"));
            accessor.tokenSecret = rt.getSecret();

            String verifier = getParam(request, "oauth_verifier");
            if (logger.isDebugEnabled()) {
                logger.debug("got oauth_verifier {}", verifier);
            }

            try {
                if (logger.isDebugEnabled()) {
                    logger.error("request token found, fetching access token for user");
                }
                AccessToken at = fetchAccessToken(accessor, rt, verifier);
                Cookie yosdk_at = at.getCookie();
                Cookie yosdk_rt = new Cookie("yosdk_rt", "");
                yosdk_at.setMaxAge(30 * 24 * 60 * 60);
                yosdk_rt.setMaxAge(0);
                response.addCookie(yosdk_at);
                response.addCookie(yosdk_rt);
                String appId = oauthConfig.getProperty("yos.appid");
                YahooSession yahooSession = new YahooSession(client, consumer, at, appId);
                request.setAttribute("yahooSession", yahooSession);
            } catch (URISyntaxException ex) {
                throw new ServletException(ex);
            } catch (OAuthException ex) {
                clearSession(request, response);
                if (redirect) {
                    redirectForAuthorization(accessor, request, response);
                    return;
                } else {
                    throw new ServletException(ex);
                }
            }
        } catch (JSONException e) {
            throw new ServletException(e);
        }
    }

    filterChain.doFilter(servletRequest, servletResponse);
}

From source file:org.apache.sling.auth.xing.login.impl.XingLoginAuthenticationHandler.java

protected void deleteCookies(final HttpServletRequest request, final HttpServletResponse response) {
    final Cookie[] cookies = request.getCookies();
    if (cookies != null) {
        for (final Cookie cookie : cookies) {
            final String name = cookie.getName();
            logger.debug("cookie found: '{}'", name);
            if (name.equals(xingCookie) || name.equals(userCookie) || name.equals(userIdCookie)) {
                logger.debug("deleting cookie '{}' with value '{}'", cookie.getName(), cookie.getValue());
                cookie.setValue(null);/* ww w. j ava2  s  .co m*/
                cookie.setMaxAge(0);
                response.addCookie(cookie);
            }
        }
    }
}

From source file:csns.web.filter.DepartmentFilter.java

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
        FilterChain filterChain) throws ServletException, IOException {
    String contextPath = request.getContextPath();
    String path = request.getRequestURI().substring(contextPath.length());
    Cookie cookie = WebUtils.getCookie(request, "default-dept");

    if (path.startsWith("/department/")) {
        int beginIndex = "/department/".length();
        int endIndex = path.indexOf("/", beginIndex);
        if (endIndex < 0)
            endIndex = path.length();/*from  w w w  .j ava 2  s  .c o  m*/
        String dept = path.substring(beginIndex, endIndex);
        request.setAttribute("dept", dept);

        logger.debug(path + " -> " + dept);

        if (cookie == null) {
            cookie = new Cookie("default-dept", dept);
            cookie.setPath("/");
            cookie.setMaxAge(100000000);
            response.addCookie(cookie);
        }
    } else {
        if (cookie != null)
            request.setAttribute("dept", cookie.getValue());
    }

    filterChain.doFilter(request, response);
}