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.appeligo.search.actions.BaseAction.java

protected String getCookieId() {
    Cookie[] cookies = getServletRequest().getCookies();
    if (cookies != null) {
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals(BaseAction.COOKIE_ID)) {
                cookie.setMaxAge(Integer.MAX_VALUE);
                return cookie.getValue();
            }/*from   ww w.ja  v  a2  s. c om*/
        }
    }
    //No cookie found;
    String cookieValue = request.getRemoteAddr() + System.currentTimeMillis();
    Cookie cookie = new Cookie(COOKIE_ID, cookieValue);
    cookie.setMaxAge(Integer.MAX_VALUE);
    response.addCookie(cookie);
    return cookieValue;
}

From source file:com.vmware.identity.openidconnect.server.LoginTest.java

@Test
public void testLoginStringWithSessionCookieMatching() throws Exception {
    // if request has both a loginString and session cookie, then if the session cookie matches, use it and ignore the loginString
    String loginString = passwordLoginString();
    Cookie sessionCookie = new Cookie(SESSION_COOKIE_NAME, SESSION_ID);
    Pair<ModelAndView, MockHttpServletResponse> result = doRequest(loginString, sessionCookie);
    ModelAndView modelView = result.getLeft();
    MockHttpServletResponse response = result.getRight();
    Assert.assertNull("modelView", modelView);
    boolean ajaxRequest = false; // it is actually an ajax request but then TestContext would expect a session cookie to be returned
    validateAuthnSuccessResponse(response, Flow.AUTHZ_CODE, Scope.OPENID, false, ajaxRequest, STATE, NONCE);
}

From source file:org.carewebframework.ui.FrameworkWebSupport.java

/**
 * Sets a cookie into the response. Cookies are URLEncoded for consistency (Version 0+ of
 * Cookies)/*from   w  ww  . ja v a  2s. com*/
 * 
 * @param cookieName Name of cookie.
 * @param value Value of cookie. If null, the cookie is removed from the client if it exists.
 * @param httpResponse Response object.
 * @param httpRequest Request object.
 * @return Newly created cookie.
 * @throws IllegalArgumentException if cookieName, httpResponse, or httpRequest arguments are
 *             null
 */
public static Cookie setCookie(final String cookieName, String value, final HttpServletResponse httpResponse,
        final HttpServletRequest httpRequest) {
    Validate.notNull(httpResponse, "The httpResponse must not be null");
    Cookie cookie = getCookie(cookieName, httpRequest);
    if (value != null) {
        value = encodeCookieValue(value);
    }

    if (cookie == null) {
        if (value == null) {
            return null;
        }
        cookie = new Cookie(cookieName, value);
    } else if (value == null) {
        cookie.setMaxAge(0);
    } else {
        cookie.setValue(value);
    }

    if (httpRequest.isSecure()) {
        cookie.setSecure(true);
    }

    httpResponse.addCookie(cookie);
    return cookie;
}

From source file:com.liferay.portal.servlet.MainServlet.java

public void service(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException {

    if (!PortalInstances.matches()) {
        String html = ContentUtil.get("messages/en_US/init.html");

        res.getOutputStream().print(html);

        return;/*from  ww w.  j a  v a 2s.co m*/
    }

    if (ShutdownUtil.isShutdown()) {
        String html = ContentUtil.get("messages/en_US/shutdown.html");

        res.getOutputStream().print(html);

        return;
    }
    req.setAttribute("dotcache", "no");
    // Shared session

    HttpSession ses = req.getSession();

    if (!GetterUtil.getBoolean(PropsUtil.get(PropsUtil.TCK_URL))) {
        String sharedSessionId = CookieUtil.get(req.getCookies(), CookieKeys.SHARED_SESSION_ID);

        _log.debug("Shared session id is " + sharedSessionId);

        if (sharedSessionId == null) {
            sharedSessionId = PwdGenerator.getPassword(PwdGenerator.KEY1 + PwdGenerator.KEY2, 12);

            Cookie sharedSessionIdCookie = new Cookie(CookieKeys.SHARED_SESSION_ID, sharedSessionId);
            sharedSessionIdCookie.setPath("/");
            sharedSessionIdCookie.setMaxAge(86400);

            res.addCookie(sharedSessionIdCookie);

            _log.debug("Shared session id is " + sharedSessionId);
        }

        // if (ses.getAttribute(WebKeys.SHARED_SESSION_ID) == null) {
        ses.setAttribute(WebKeys.SHARED_SESSION_ID, sharedSessionId);
        // }

        HttpSession portalSes = (HttpSession) SharedSessionPool.get(sharedSessionId);

        if ((portalSes == null) || (ses != portalSes)) {
            if (portalSes == null) {
                _log.debug("No session exists in pool");
            } else {
                _log.debug("Session " + portalSes.getId() + " in pool is old");
            }

            _log.debug("Inserting current session " + ses.getId() + " in pool");

            SharedSessionPool.put(sharedSessionId, ses);
        }
    }

    // Test CAS auto login

    /*
     * ses.setAttribute(
     * com.liferay.portal.auth.CASAutoLogin.CAS_FILTER_USER,
     * "liferay.com.1");
     */

    // CTX

    ServletContext ctx = getServletContext();
    ServletContext portalCtx = ctx.getContext(PropsUtil.get(PropsUtil.PORTAL_CTX));
    if (portalCtx == null) {
        portalCtx = ctx;
    }

    req.setAttribute(WebKeys.CTX, portalCtx);

    // CTX_PATH variable

    String ctxPath = (String) ctx.getAttribute(WebKeys.CTX_PATH);

    if (portalCtx.getAttribute(WebKeys.CTX_PATH) == null) {
        portalCtx.setAttribute(WebKeys.CTX_PATH, ctxPath);
    }

    if (ses.getAttribute(WebKeys.CTX_PATH) == null) {
        ses.setAttribute(WebKeys.CTX_PATH, ctxPath);
    }

    req.setAttribute(WebKeys.CTX_PATH, ctxPath);

    // CAPTCHA_PATH variable

    String captchaPath = (String) ctx.getAttribute(WebKeys.CAPTCHA_PATH);

    if (portalCtx.getAttribute(WebKeys.CAPTCHA_PATH) == null) {
        portalCtx.setAttribute(WebKeys.CAPTCHA_PATH, captchaPath);
    }

    if (ses.getAttribute(WebKeys.CAPTCHA_PATH) == null) {
        ses.setAttribute(WebKeys.CAPTCHA_PATH, captchaPath);
    }

    req.setAttribute(WebKeys.CAPTCHA_PATH, captchaPath);

    // IMAGE_PATH variable

    String imagePath = (String) ctx.getAttribute(WebKeys.IMAGE_PATH);

    if (portalCtx.getAttribute(WebKeys.IMAGE_PATH) == null) {
        portalCtx.setAttribute(WebKeys.IMAGE_PATH, imagePath);
    }

    if (ses.getAttribute(WebKeys.IMAGE_PATH) == null) {
        ses.setAttribute(WebKeys.IMAGE_PATH, imagePath);
    }

    req.setAttribute(WebKeys.IMAGE_PATH, imagePath);

    // WebKeys.COMPANY_ID variable

    String companyId = (String) ctx.getAttribute(WebKeys.COMPANY_ID);

    if (portalCtx.getAttribute(WebKeys.COMPANY_ID) == null) {
        portalCtx.setAttribute(WebKeys.COMPANY_ID, companyId);
    }

    if (ses.getAttribute(WebKeys.COMPANY_ID) == null) {
        ses.setAttribute(WebKeys.COMPANY_ID, companyId);
    }

    req.setAttribute(WebKeys.COMPANY_ID, companyId);

    // Portlet Request Processor

    PortletRequestProcessor portletReqProcessor = (PortletRequestProcessor) portalCtx
            .getAttribute(WebKeys.PORTLET_STRUTS_PROCESSOR);

    if (portletReqProcessor == null) {
        portletReqProcessor = new PortletRequestProcessor(this, getModuleConfig(req));

        portalCtx.setAttribute(WebKeys.PORTLET_STRUTS_PROCESSOR, portletReqProcessor);
    }

    // Tiles definitions factory

    if (portalCtx.getAttribute(TilesUtilImpl.DEFINITIONS_FACTORY) == null) {
        portalCtx.setAttribute(TilesUtilImpl.DEFINITIONS_FACTORY,
                ctx.getAttribute(TilesUtilImpl.DEFINITIONS_FACTORY));
    }

    // Set character encoding

    String strutsCharEncoding = PropsUtil.get(PropsUtil.STRUTS_CHAR_ENCODING);

    req.setCharacterEncoding(strutsCharEncoding);

    /*
     * if (!BrowserSniffer.is_wml(req)) { res.setContentType(
     * Constants.TEXT_HTML + "; charset=" + strutsCharEncoding); }
     */

    // Determine content type

    String contentType = req.getHeader("Content-Type");

    if ((contentType != null) && (contentType.startsWith("multipart/form-data"))) {

        req = new UploadServletRequest(req);
    } else if (ParamUtil.get(req, WebKeys.ENCRYPT, false)) {
        try {
            Company company = CompanyLocalManagerUtil.getCompany(companyId);

            req = new EncryptedServletRequest(req, company.getKeyObj());
        } catch (Exception e) {
        }
    }

    // Current URL

    String completeURL = Http.getCompleteURL(req);
    if (completeURL.indexOf("j_security_check") != -1) {
        completeURL = ctxPath;
    } else {
        completeURL = completeURL.substring(completeURL.indexOf("://") + 3, completeURL.length());

        completeURL = completeURL.substring(completeURL.indexOf("/"), completeURL.length());
    }

    req.setAttribute(WebKeys.CURRENT_URL, completeURL);

    // Chat server

    // Login

    String userId = PortalUtil.getUserId(req);

    if ((userId != null)) {
        PrincipalThreadLocal.setName(userId);
    }

    if (userId == null) {
        try {
            User user = UserManagerUtil.getDefaultUser(companyId);
            if (ses.getAttribute(Globals.LOCALE_KEY) == null)
                ses.setAttribute(Globals.LOCALE_KEY, user.getLocale());

        } catch (Exception e) {
            Logger.error(this, e.getMessage(), e);
        }
    }

    // Process pre service events

    try {
        EventsProcessor.process(PropsUtil.getArray(PropsUtil.SERVLET_SERVICE_EVENTS_PRE), req, res);
    } catch (Exception e) {
        Logger.error(this, e.getMessage(), e);

        req.setAttribute(PageContext.EXCEPTION, e);

        StrutsUtil.forward(PropsUtil.get(PropsUtil.SERVLET_SERVICE_EVENTS_PRE_ERROR_PAGE), portalCtx, req, res);
    }

    // Struts service

    callParentService(req, res);

    // Process post service events

    try {
        EventsProcessor.process(PropsUtil.getArray(PropsUtil.SERVLET_SERVICE_EVENTS_POST), req, res);
    } catch (Exception e) {
        Logger.error(this, e.getMessage(), e);
    }

    // Clear the principal associated with this thread

    PrincipalThreadLocal.setName(null);
}

From source file:com.maydesk.base.PDUserSession.java

public void setCookie(String cookieName, String value) {
    Cookie userCookie = new Cookie(cookieName, value);
    ContainerContext ctx = (ContainerContext) ApplicationInstance.getActive()
            .getContextProperty(ContainerContext.CONTEXT_PROPERTY_NAME);
    userCookie.setMaxAge(60 * 60 * 24 * 360); // expires after 360 days
    ctx.addCookie(userCookie);/*  w  w w  .j a  va  2  s  .  c  o  m*/
}

From source file:net.lightbody.bmp.proxy.jetty.http.HttpResponse.java

/** Add a Set-Cookie field.
 */
public void addSetCookie(String name, String value) {
    _header.addSetCookie(new Cookie(name, value));
}

From source file:cn.vlabs.umt.ui.servlet.login.LoginMethod.java

/**
 * ??cookie/*w  w  w  . j  av  a  2  s.c  o m*/
 * */
public static void generateSsoCookie(HttpServletResponse response, HttpServletRequest request,
        LoginInfo loginInfo) throws UnsupportedEncodingException {
    PCookie pcookie = (PCookie) ServiceFactory.getBean(request, "PCookie");
    // Pcookie
    String encrypted = pcookie
            .encrypt(loginInfo.getUser().getCstnetId() + "/" + RequestUtil.getRemoteIP(request) + "/"
                    + loginInfo.getPasswordType() + "/" + System.currentTimeMillis());
    Cookie cookie = new Cookie(Attributes.COOKIE_NAME, encrypted);
    cookie.setPath("/");
    cookie.setMaxAge(MAX_COOKIE_AGE);
    response.addCookie(cookie);
    Cookie umtIdCookie = new Cookie(Attributes.SSO_FLAG, SessionUtils.getUserId(request) + "");
    umtIdCookie.setDomain(Attributes.SSO_FLAG_DOMAIN);
    umtIdCookie.setPath("/");
    umtIdCookie.setMaxAge(LoginMethod.MAX_COOKIE_AGE);
    response.addCookie(umtIdCookie);
}

From source file:it.scoppelletti.programmerpower.web.security.SsoRememberMeServices.java

/**
 * Inizializza il cookie per l&rsquo;autenticazione persistente.
 * //from w w w  . j a va2s . c o m
 * @param  value  Valore.
 * @param  maxAge Scadenza.
 * @return        Oggetto.
 */
private Cookie buildCookie(String value, int maxAge) {
    Cookie cookie;

    cookie = new Cookie(getCookieName(), value);
    if (myCookieDomain != null) {
        cookie.setDomain(myCookieDomain);
    }
    cookie.setPath(myCookiePath);
    cookie.setMaxAge(maxAge);

    return cookie;
}

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  2s.c o  m

    registerLogin(vc, user);
}

From source file:ai.susi.server.AbstractAPIHandler.java

/**
 * Delete the login cookie if present//from  w w w .java  2s .  com
 * @param response
 */
protected static void deleteLoginCookie(HttpServletResponse response) {
    Cookie deleteCookie = new Cookie("login", null);
    deleteCookie.setPath("/");
    deleteCookie.setMaxAge(0);
    response.addCookie(deleteCookie);
}