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:com.activecq.tools.auth.impl.CookieAuthenticationImpl.java

/**
 *
 * @param userId/*  w w  w.j  av a 2  s .  co m*/
 * @param cookiePath
 * @param expiry
 * @return
 */
private Cookie createSessionAuthenticationCookie(String userId, String cookiePath, int expiry) {
    try {
        long expiriesAt = new Date().getTime();

        if (expiry > 0) {
            expiriesAt += (expiry * 1000); // seconds to millseconds
        }

        final String timestamp = String.valueOf(expiriesAt);
        String cookieData = createCookieData(userId, timestamp);

        Cookie cookie = new Cookie(cookieName, cookieData);
        cookie.setPath(cookiePath);
        cookie.setMaxAge(expiry); // in seconds

        return cookie;
    } catch (UnsupportedEncodingException ex) {
        Logger.getLogger(CookieAuthenticationImpl.class.getName()).log(Level.SEVERE, null, ex);
    } catch (NoSuchAlgorithmException ex) {
        Logger.getLogger(CookieAuthenticationImpl.class.getName()).log(Level.SEVERE, null, ex);
    } catch (InvalidKeyException ex) {
        Logger.getLogger(CookieAuthenticationImpl.class.getName()).log(Level.SEVERE, null, ex);
    }

    return null;
}

From source file:org.ngrinder.user.controller.UserController.java

/**
 * Switch user identity./*from w w  w.  j  a  v a2 s .c o  m*/
 *
 * @param model    model
 * @param to       the user to whom a user will switch
 * @param response response
 * @return redirect:/perftest/
 */
@RequestMapping("/switch")
public String switchUser(@RequestParam(required = false, defaultValue = "") String to,
        HttpServletRequest request, HttpServletResponse response, ModelMap model) {
    Cookie cookie = new Cookie("switchUser", to);
    cookie.setPath("/");
    // Delete Cookie if empty switchUser
    if (StringUtils.isEmpty(to)) {
        cookie.setMaxAge(0);
    }

    response.addCookie(cookie);
    model.clear();
    final String referer = request.getHeader("referer");
    return "redirect:" + StringUtils.defaultIfBlank(referer, "/");
}

From source file:com.persistent.cloudninja.controller.TenantProfileController.java

@RequestMapping(value = "{tenantId}/showTenantProfilePage.htm", method = RequestMethod.POST)
public ModelAndView showProfilePage(HttpServletRequest request, HttpServletResponse response,
        @CookieValue(value = "CLOUDNINJAAUTH", required = false) String cookie,
        @ModelAttribute("logoFileDTO") LogoFileDTO logoFileDTO, BindingResult result) {
    // validate the file uploaded for logo
    logoFileDTOValidator.validate(logoFileDTO, result);
    // if no errors in validation then only process the request
    if (!result.hasErrors()) {
        if (cookie == null) {
            cookie = request.getAttribute("cookieNameAttr").toString();
        }//from   w w w.j a  v a2 s  . c  om
        String tenantId = AuthFilterUtils
                .getFieldValueFromCookieString(CloudNinjaConstants.COOKIE_TENANTID_PREFIX, cookie);

        String logoFileName = fileUploadService.fileUploadService(logoFileDTO.getFile(), tenantId);

        String logoCookieName = "CLOUDNINJALOGO";

        // update the logo cookie with the new logo file
        Cookie cookies[] = request.getCookies();
        Cookie logoCookie = null;
        if (cookies != null) {
            for (int i = 0; i < cookies.length; i++) {
                if (cookies[i].getName().equals(logoCookieName)) {
                    logoCookie = cookies[i];
                    logoCookie.setValue(logoFileName);
                    logoCookie.setMaxAge(-1);
                    logoCookie.setPath("/");
                    response.addCookie(logoCookie);
                    break;
                }
            }
        }
    }

    return new ModelAndView("tenantProfilePage", "logoFileDTO", logoFileDTO);
}

From source file:com.alibaba.dubbo.governance.web.governance.module.screen.Providers.java

/**
 * searchcookie?/* w w w .  j ava 2 s  .  com*/
 * ??cookie?????
 * @param context
 * @param value
 */
private void setSearchHistroy(Map<String, Object> context, String value) {
    //?cookie
    String separatorsB = "\\.\\.\\.\\.\\.\\.";
    String newCookiev = value;
    Cookie[] cookies = request.getCookies();
    for (Cookie c : cookies) {
        if (c.getName().equals("HISTORY")) {
            String cookiev = c.getValue();
            String[] values = cookiev.split(separatorsB);
            int count = 1;
            for (String v : values) {
                if (count <= 10) {
                    if (!value.equals(v)) {
                        newCookiev = newCookiev + separatorsB + v;
                    }
                }
                count++;
            }
            break;
        }
    }

    Cookie _cookie = new Cookie("HISTORY", newCookiev);
    _cookie.setMaxAge(60 * 60 * 24 * 7); // Cookie30
    _cookie.setPath("/");
    response.addCookie(_cookie); // 
}

From source file:org.guanxi.idp.service.GenericAuthHandler.java

protected boolean auth(String spEntityID, HttpServletRequest request, HttpServletResponse response) {
    // Look for our cookie. This is after any application cookie handler has authenticated the user
    String cookieName = getCookieName();
    Cookie[] cookies = request.getCookies();
    if (cookies != null) {
        for (int c = 0; c < cookies.length; c++) {
            if (cookies[c].getName().equals(cookieName)) {
                // Retrieve the principal from the servlet context
                if (servletContext.getAttribute(cookies[c].getValue()) == null) {
                    // Out of date cookie value, so remove the cookie
                    cookies[c].setMaxAge(0);
                    response.addCookie(cookies[c]);
                } else {
                    // Found the principal from a previously established authentication
                    request.setAttribute(Guanxi.REQUEST_ATTR_IDP_PRINCIPAL,
                            (GuanxiPrincipal) servletContext.getAttribute(cookies[c].getValue()));
                    return true;
                }/* ww w . j av a2  s  .c  o m*/
            }
        }
    }

    // Are we getting an authentication request from the login page?
    if (request.getParameter("guanxi:mode") != null) {
        if (request.getParameter("guanxi:mode").equalsIgnoreCase("authenticate")) {
            // Get a new GuanxiPrincipal...
            GuanxiPrincipal principal = gxPrincipalFactory.createNewGuanxiPrincipal(request);
            if (authenticator.authenticate(principal, request.getParameter("userid"),
                    request.getParameter("password"))) {
                // ...associate it with a login name...
                if (principal.getName() == null) {
                    //The login name from the authenticator page
                    principal.setName(request.getParameter("userid"));
                }
                // ...store it in the request for the SSO to use...
                request.setAttribute(Guanxi.REQUEST_ATTR_IDP_PRINCIPAL, principal);
                // ...and store it in application scope for the rest of the profile to use
                servletContext.setAttribute(principal.getUniqueId(), principal);

                // Get a new cookie ready to reference the principal in the servlet context
                Cookie cookie = new Cookie(getCookieName(), principal.getUniqueId());
                cookie.setDomain((String) servletContext.getAttribute(Guanxi.CONTEXT_ATTR_IDP_COOKIE_DOMAIN));
                cookie.setPath(idpConfig.getCookie().getPath());
                if (((Integer) (servletContext.getAttribute(Guanxi.CONTEXT_ATTR_IDP_COOKIE_AGE)))
                        .intValue() != -1)
                    cookie.setMaxAge(
                            ((Integer) (servletContext.getAttribute(Guanxi.CONTEXT_ATTR_IDP_COOKIE_AGE)))
                                    .intValue());
                response.addCookie(cookie);

                return true;
            } // if (authenticator.authenticate...
            else {
                logger.error("Authentication error : " + authenticator.getErrorMessage());
                request.setAttribute("message",
                        messageSource.getMessage("authentication.error", null, request.getLocale()));
                try {
                    request.getRequestDispatcher(errorPage).forward(request, response);
                } catch (Exception e) {
                    logger.error("Could not display authentication error page", e);
                }
                return false;
            }
        }
    } // if (request.getParameter("guanxi:mode") != null) {

    // No embedded cookie authentication or local auth, so show the login page
    String authPage = null;
    AuthPage[] authPages = idpConfig.getAuthenticatorPages().getAuthPageArray();
    for (int c = 0; c < authPages.length; c++) {
        // We'll use the default auth page if none is specified for this service provider
        if (authPages[c].getProviderId().equals(Guanxi.DEFAULT_AUTH_PAGE_MARKER)) {
            authPage = authPages[c].getUrl();
        }

        // Customised auth page for this service provider
        if (authPages[c].getProviderId().equals(request.getParameter(spEntityID))) {
            authPage = authPages[c].getUrl();
        }
    }

    addRequiredParamsAsPrefixedAttributes(request);
    try {
        request.getRequestDispatcher(authPage).forward(request, response);
    } catch (Exception e) {
        logger.error("Could not display authentication page", e);
    }

    return false;
}

From source file:com.jredrain.session.HttpSessionFilter.java

private Cookie generateCookie(HttpServletRequest request, HttpServletResponse response) {
    Cookie sessionIdCookie;
    String sid = null;// w w w. j  a  va2s  .c  o m
    if (StringUtils.isBlank(sid)) {
        sid = CommonUtils.uuid();
    }
    sessionIdCookie = new Cookie(sessionIdCookieName, sid);

    String domain = request.getServerName();

    if (domain != null) {
        sessionIdCookie.setDomain(domain);
    }

    sessionIdCookie.setPath("/");
    response.addCookie(sessionIdCookie);
    return sessionIdCookie;
}

From source file:org.jcronjob.session.HttpSessionFilter.java

private Cookie generateCookie(HttpServletRequest request, HttpServletResponse response) {
    Cookie sessionIdCookie;
    String sid = null;// w  w w .j a va 2s.co  m
    if (StringUtils.isBlank(sid)) {
        sid = generateUUID();
    }
    sessionIdCookie = new Cookie(sessionIdCookieName, sid);

    String domain = request.getServerName();

    if (domain != null) {
        sessionIdCookie.setDomain(domain);
    }

    sessionIdCookie.setPath("/");
    response.addCookie(sessionIdCookie);
    return sessionIdCookie;
}

From source file:azkaban.webapp.servlet.LoginAbstractAzkabanServlet.java

protected void handleAjaxLoginAction(HttpServletRequest req, HttpServletResponse resp, Map<String, Object> ret)
        throws ServletException {
    if (hasParam(req, "username") && hasParam(req, "password")) {
        Session session = null;//from w w  w.  j  a v  a2 s. co m
        try {
            session = createSession(req);
        } catch (UserManagerException e) {
            ret.put("error", "Incorrect Login. " + e.getMessage());
            return;
        }

        Cookie cookie = new Cookie(SESSION_ID_NAME, session.getSessionId());
        cookie.setPath("/");
        resp.addCookie(cookie);
        getApplication().getSessionCache().addSession(session);
        ret.put("status", "success");
        ret.put("session.id", session.getSessionId());
    } else {
        ret.put("error", "Incorrect Login.");
    }
}

From source file:org.jboss.web.loadbalancer.Loadbalancer.java

protected void parseServerResponse(HttpServletRequest request, HttpServletResponse response, HttpClient client,
        HttpMethod method) throws ServletException, IOException {
    response.setStatus(method.getStatusCode());

    //Cookies// w w w  .  j  a  va 2  s  .  c om
    org.apache.commons.httpclient.Cookie[] respCookies = client.getState().getCookies();

    for (int i = 0; i < respCookies.length; ++i) {
        Cookie cookie = new Cookie(respCookies[i].getName(), respCookies[i].getValue());

        if (respCookies[i].getPath() != null) {
            cookie.setPath(respCookies[i].getPath());
        }
        response.addCookie(cookie);
    }

    Header[] header = method.getResponseHeaders();

    for (int i = 0; i < header.length; ++i) {
        if (!ignorableHeader.contains(header[i].getName().toLowerCase())) {
            response.setHeader(header[i].getName(), header[i].getValue());
        }
    }

    copyServerResponse(response, method);
}

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

private Filter csrfHeaderFilter() {
    return new OncePerRequestFilter() {
        @Override//from w  w w  .j  a va2  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;
                }
            }
        }
    };
}