Example usage for javax.servlet.http Cookie setPath

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

Introduction

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

Prototype

public void setPath(String uri) 

Source Link

Document

Specifies a path for the cookie to which the client should return the cookie.

Usage

From source file:de.kp.ames.web.core.service.ServiceImpl.java

/**
 * A specific method to enable file download even in a secure (SSL) environment
 * //from  w  ww .j a va 2  s .c  om
 * @param file
 * @param request
 * @param response
 * @throws IOException
 */
public void sendFileDownloadResponse(FileUtil file, HttpServletRequest request, HttpServletResponse response)
        throws IOException {

    if (file == null)
        return;

    String clientPath = request.getParameter("clientpath");
    if (clientPath == null)
        return;

    /*
     * Distinguish between secure and non-secure download requests
     */
    if (request.isSecure()) {

        response.addHeader("Cache-Control", "no-cache");
        response.addHeader("Pragma", "no-cache");

        response.addHeader("Expires", "-1");

    } else {

        response.addHeader("Cache-Control", "private");
        response.addHeader("Pragma", "public");

    }

    /*
     * Determine user agent
     */
    String ua = request.getHeader("User-Agent").toLowerCase();
    boolean isIE = ((ua.indexOf("msie 6.0") != -1) || (ua.indexOf("msie 7.0") != -1)) ? true : false;

    /*
     * Encode file name
     */
    String encFileName = URLEncoder.encode(file.getFilename(), "UTF-8");

    if (isIE) {

        response.addHeader("Content-Disposition", "attachment;  filename=\"" + encFileName + "\"");
        response.addHeader("Connection", "close");

        response.setContentType("application/force-download;  name=\"" + encFileName + "\"");

    } else {

        response.addHeader("Content-Disposition", "attachment; filename=\"" + encFileName + "\"");

        response.setContentType("application/octet-stream; name=\"" + encFileName + "\"");
        response.setContentLength(file.getLength());

    }

    /*
     * Signal download ready with cookie
     */
    Cookie cookie = new Cookie("DOWNLOAD_READY", "END");
    cookie.setPath(clientPath);
    response.addCookie(cookie);

    // finally set http status
    response.setStatus(HttpServletResponse.SC_OK);

    OutputStream os = response.getOutputStream();

    os.write(file.getFile());
    os.close();

}

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.
 *//*from  ww  w  . j  a v  a 2  s. com*/
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:net.anthonychaves.bookmarks.web.PersistentLoginFilter.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {

    HttpServletRequest httpRequest = (HttpServletRequest) request;
    HttpServletResponse httpResponse = (HttpServletResponse) response;
    Cookie tokenCookie = getCookieByName(httpRequest.getCookies(), "loginToken");

    HttpSession session = httpRequest.getSession();
    User user = (User) session.getAttribute("user");

    if (user == null && tokenCookie != null) {
        user = tokenService.loginWithToken(tokenCookie.getValue());
        String tokenValue = tokenService.setupNewLoginToken(user);

        httpRequest.getSession().setAttribute("user", user);
        tokenCookie.setMaxAge(0);//from  w w w  .ja  v a 2 s  .c  om
        httpResponse.addCookie(tokenCookie);

        tokenCookie = new Cookie("loginToken", tokenValue);
        tokenCookie.setPath("/bookmarks");
        tokenCookie.setMaxAge(168 * 60 * 60);
        httpResponse.addCookie(tokenCookie);
    }

    chain.doFilter(httpRequest, httpResponse);
}

From source file:org.apache.coyote.tomcat5.CoyoteAdapter.java

/**
 * Parse cookies.//from  ww w.ja va 2 s  .c o  m
 */
protected void parseCookies(Request req, CoyoteRequest request) {

    Cookies serverCookies = req.getCookies();
    int count = serverCookies.getCookieCount();
    if (count <= 0)
        return;

    Cookie[] cookies = new Cookie[count];

    int idx = 0;
    for (int i = 0; i < count; i++) {
        ServerCookie scookie = serverCookies.getCookie(i);
        if (scookie.getName().equals(Globals.SESSION_COOKIE_NAME)) {
            // Override anything requested in the URL
            if (!request.isRequestedSessionIdFromCookie()) {
                // Accept only the first session id cookie
                request.setRequestedSessionId(scookie.getValue().toString());
                request.setRequestedSessionCookie(true);
                request.setRequestedSessionURL(false);
                if (log.isDebugEnabled())
                    log.debug(" Requested cookie session id is "
                            + ((HttpServletRequest) request.getRequest()).getRequestedSessionId());
            }
        }
        try {
            Cookie cookie = new Cookie(scookie.getName().toString(), scookie.getValue().toString());
            cookie.setPath(scookie.getPath().toString());
            cookie.setVersion(scookie.getVersion());
            String domain = scookie.getDomain().toString();
            if (domain != null) {
                cookie.setDomain(scookie.getDomain().toString());
            }
            cookies[idx++] = cookie;
        } catch (Exception ex) {
            log.error("Bad Cookie Name: " + scookie.getName() + " /Value: " + scookie.getValue(), ex);
        }
    }
    if (idx < count) {
        Cookie[] ncookies = new Cookie[idx];
        System.arraycopy(cookies, 0, ncookies, 0, idx);
        cookies = ncookies;
    }

    request.setCookies(cookies);

}

From source file:com.activecq.experiments.redis.impl.RedisSessionUtilImpl.java

@Override
public Cookie createSessionCookie() {
    final Cookie cookie = new Cookie(this.getSessionCookieName(), java.util.UUID.randomUUID().toString());

    cookie.setPath("/");
    cookie.setSecure(this.secureCookie);

    // Expire with browser session
    cookie.setMaxAge(-1);/*w w  w . j ava  2  s. c o  m*/

    return cookie;
}

From source file:com.sourcesense.confluence.servlets.CMISProxyServlet.java

/**
 * Retrieves all of the cookies from the servlet request and sets them on
 * the proxy request/* w  w  w .j a v  a 2s. com*/
 *
 * @param httpServletRequest     The request object representing the client's
 *                               request to the servlet engine
 * @param httpMethodProxyRequest The request that we are about to send to
 *                               the proxy host
 */
private void setProxyRequestCookies(HttpServletRequest httpServletRequest, HttpMethod httpMethodProxyRequest) {
    // Get an array of all of all the cookies sent by the client
    Cookie[] cookies = httpServletRequest.getCookies();
    if (cookies == null) {
        return;
    }

    for (Cookie cookie : cookies) {
        cookie.setDomain(stringProxyHost);
        cookie.setPath(httpServletRequest.getServletPath());
        httpMethodProxyRequest.setRequestHeader("Cookie",
                cookie.getName() + "=" + cookie.getValue() + "; Path=" + cookie.getPath());
    }
}

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);/*www .j  a  va  2 s  . c o m*/
    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:org.apache.hive.service.cli.thrift.ThriftHttpServlet.java

/**
 * Generate a server side cookie given the cookie value as the input.
 * @param str Input string token.//from w  w  w .  j a  va 2 s  .c  om
 * @return The generated cookie.
 * @throws UnsupportedEncodingException
 */
private Cookie createCookie(String str) throws UnsupportedEncodingException {
    if (LOG.isDebugEnabled()) {
        LOG.debug("Cookie name = " + AUTH_COOKIE + " value = " + str);
    }
    Cookie cookie = new Cookie(AUTH_COOKIE, str);

    cookie.setMaxAge(cookieMaxAge);
    if (cookieDomain != null) {
        cookie.setDomain(cookieDomain);
    }
    if (cookiePath != null) {
        cookie.setPath(cookiePath);
    }
    cookie.setSecure(isCookieSecure);
    return cookie;
}

From source file:com.nkapps.billing.services.SearchServiceImpl.java

@Override
public String execSearchBy(HttpServletRequest request, HttpServletResponse response) throws Exception {
    Cookie sbtCookie = null;

    String searchBy = request.getParameter("searchBy");
    if (searchBy == null) {
        Cookie[] requestCookies = request.getCookies();
        for (Cookie c : requestCookies) {
            if (c.getName().equals("searchBy")) {
                sbtCookie = c;//  w w  w.j  ava  2 s.co  m
            }
        }
        if (sbtCookie != null) {
            searchBy = URLDecoder.decode(sbtCookie.getValue(), "UTF-8");
        } else {
            searchBy = "";
        }
    } else {
        sbtCookie = new Cookie("searchBy", URLEncoder.encode(searchBy, "UTF-8"));
        sbtCookie.setPath("/");
        response.addCookie(sbtCookie);
    }
    return searchBy;
}

From source file:org.infoscoop.web.SessionManagerFilter.java

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    HttpServletRequest httpReq = (HttpServletRequest) request;
    if (log.isDebugEnabled()) {
        log.debug("Enter SessionManagerFilter form " + httpReq.getRequestURI());
    }//w ww.  j av a  2  s  . c  o  m

    if (request instanceof javax.servlet.http.HttpServletRequest) {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;

        String uid = null;
        if (SessionCreateConfig.doLogin()) {
            uid = getUidFromSession(httpReq);

            if (uid != null) {
                addUidToSession(uid, request);
            }

            if (redirectPaths.contains(httpReq.getServletPath())) {
                httpResponse.addCookie(new Cookie("redirect_path", httpReq.getServletPath()));
            }
            if (uid == null && !isExcludePath(httpReq.getServletPath())) {
                if (httpRequest.getHeader("MSDPortal-Ajax") != null) {
                    if (log.isInfoEnabled())
                        log.info("session timeout has occured. logoff automatically.");
                    httpResponse.setHeader(HttpStatusCode.HEADER_NAME, HttpStatusCode.MSD_SESSION_TIMEOUT);
                    httpResponse.sendError(500);
                    return;
                }
            }
        } else {
            uid = getUidFromHeader(httpReq);
            if (uid == null)
                uid = getUidFromSession(httpReq);
            if (uid != null) {
                addUidToSession(uid, request);
            }
        }

        if (uid == null) {
            Cookie[] cookies = httpReq.getCookies();
            if (cookies != null) {
                for (Cookie cookie : cookies) {
                    if (cookie.getName().equals("portal-credential")) {
                        int keepPeriod = 7;
                        try {
                            keepPeriod = Integer.parseInt(PropertiesDAO.newInstance()
                                    .findProperty("loginStateKeepPeriod").getValue());
                        } catch (Exception ex) {
                            log.warn("", ex);
                        }

                        if (keepPeriod <= 0) {
                            Cookie credentialCookie = new Cookie("portal-credential", "");
                            credentialCookie.setMaxAge(0);
                            credentialCookie.setPath("/");
                            httpResponse.addCookie(credentialCookie);

                            log.info("clear auto login credential [" + credentialCookie.getValue() + "]");
                        } else {
                            try {
                                uid = tryAutoLogin(cookie);
                                httpReq.getSession().setAttribute("Uid", uid);

                                log.info("auto login success.");
                            } catch (Exception ex) {
                                log.info("auto login failed.", ex);
                            }
                        }
                    }
                }
            }
        }

        if (uid == null && SessionCreateConfig.doLogin() && !isExcludePath(httpReq.getServletPath())) {
            String requestUri = httpReq.getRequestURI();
            String loginUrl = requestUri.lastIndexOf("/manager/") > 0
                    ? requestUri.substring(0, requestUri.lastIndexOf("/")) + "/../login.jsp"
                    : "login.jsp";

            httpResponse.sendRedirect(loginUrl);
            return;
        }

        if (log.isInfoEnabled())
            log.info("### Access from user " + uid + " to " + httpReq.getRequestURL());

        // fix #42
        //         setUserInfo2Cookie(httpReq, (HttpServletResponse)response, uid);
        HttpSession session = httpRequest.getSession();

        Subject loginUser = (Subject) session.getAttribute(LOGINUSER_SUBJECT_ATTR_NAME);

        if (loginUser == null || (isChangeLoginUser(uid, loginUser)
                && !(session instanceof PreviewImpersonationFilter.PreviewHttpSession))) {
            if (!SessionCreateConfig.getInstance().hasUidHeader() && uid != null) {
                AuthenticationService service = AuthenticationService.getInstance();
                try {
                    if (service != null)
                        loginUser = service.getSubject(uid);
                } catch (Exception e) {
                    log.error("", e);
                }
            }

            if (loginUser == null || isChangeLoginUser(uid, loginUser)) {
                loginUser = new Subject();
                loginUser.getPrincipals().add(new ISPrincipal(ISPrincipal.UID_PRINCIPAL, uid));
            }

            setLoginUserName(httpRequest, loginUser);

            for (Map.Entry entry : SessionCreateConfig.getInstance().getRoleHeaderMap().entrySet()) {
                String headerName = (String) entry.getKey();
                String roleType = (String) entry.getValue();
                Enumeration headerValues = httpRequest.getHeaders(headerName);
                while (headerValues.hasMoreElements()) {
                    String headerValue = (String) headerValues.nextElement();
                    try {
                        Set principals = loginUser.getPrincipals();
                        principals.add(new ISPrincipal(roleType, headerValue));
                        //                     loginUser.getPrincipals().add( roleType.getConstructor(paramTypes).newInstance(initArgs) );
                        if (log.isInfoEnabled())
                            log.info("Set principal to login subject: " + roleType + "=" + headerValue);
                    } catch (IllegalArgumentException e) {
                        log.error("", e);
                    } catch (SecurityException e) {
                        log.error("", e);
                    }
                }

            }
            session.setAttribute(LOGINUSER_SUBJECT_ATTR_NAME, loginUser);
        }
        SecurityController.registerContextSubject(loginUser);
        if (httpRequest.getHeader("X-IS-TIMEZONE") != null) {
            int timeZoneOffset = 0;
            try {
                timeZoneOffset = Integer.parseInt(httpRequest.getHeader("X-IS-TIMEZONE"));
            } catch (NumberFormatException e) {
                if (log.isDebugEnabled())
                    log.debug(httpRequest.getHeader("X-IS-TIMEZONE"), e);
            } finally {
                UserContext.instance().getUserInfo().setClientTimezoneOffset(timeZoneOffset);
            }
        }
    }
    chain.doFilter(request, response);

    if (log.isDebugEnabled()) {
        log.debug("Exit SessionManagerFilterform " + httpReq.getRequestURI());
    }

}