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.mmj.app.common.cookie.parser.CookieNameHelper.java

/**
 * ????CookieName?Response//from  ww  w. j a v a  2 s. c o m
 * 
 * <pre>
 * cookie<code>null</code>blankCookie
 * </pre>
 */
public void saveIfModified(HttpServletResponse response) {
    if (!isModified) {
        return;
    }
    String value = config.isSimpleValue() ? simpleValue : CookieUtils.mapToStr(allCookieKeyValues);
    if (config.isEncrypt()) {
        value = EncryptBuilder.getInstance().encrypt(value);
    }
    Cookie cookie = new Cookie(cookieName, value);
    if (StringUtils.isBlank(value)) {
        cookie.setMaxAge(CookieMaxAge.OUT_OF_DATE);
    } else {
        cookie.setMaxAge(config.getMaxAge());
    }
    cookie.setDomain(config.getDomain().getDomain());
    cookie.setPath(config.getPath().getPath());
    response.addCookie(cookie);

    // ?????
    this.isModified = false;
}

From source file:cec.easyshop.storefront.security.cookie.EnhancedCookieGeneratorTest.java

@Test
public void testServerSideCookieDefaultPath() {
    cookieGenerator.setCookieName("guid");
    cookieGenerator.setHttpOnly(true);//server side
    BDDMockito.given(request.getContextPath()).willReturn("/");
    cookieGenerator.addCookie(response, "cookie_monster");
    cookieGenerator.setUseDefaultPath(false);

    final Cookie expectedCookie = new Cookie("guid", "cookie_monster");
    expectedCookie.setPath("/");
    expectedCookie.setSecure(false);//w  w w .j  av  a2s  .  co m
    expectedCookie.setMaxAge(NEVER_EXPIRES);
    expectedCookie.setDomain("what a domain");

    Mockito.verify(response).addHeader(EnhancedCookieGenerator.HEADER_COOKIE,
            "guid=cookie_monster; Version=1; Domain=\"what a domain\"; Path=/; HttpOnly");
}

From source file:edu.utah.further.i2b2.hook.further.web.ServletUtil.java

/**
 * Convenience method to set a cookie. The cookie gets max age set to 30 days.
 *
 * @param response/*from w  ww .j  a  v a2s  .c o  m*/
 *            response that will accept a cookie
 * @param name
 *            name of the cookie to store
 * @param value
 *            value of the cookie
 * @param path
 *            path of the cookie
 */
public static void setCookie(final HttpServletResponse response, final String name, final String value,
        final String path) {
    if (log.isDebugEnabled()) {
        log.debug("Setting cookie " + quote(name) + " on path " + quote(path));
    }

    final Cookie cookie = new Cookie(name, value);
    cookie.setSecure(false);
    cookie.setPath(path);
    cookie.setMaxAge(3600 * 24 * 30); // 30 days

    response.addCookie(cookie);
}

From source file:net.bluehornreader.web.WebUtils.java

private static void saveCookie(HttpServletResponse httpServletResponse, boolean secured, String name,
        String value, int expires) {
    Cookie cookie = new Cookie(name, value);
    cookie.setHttpOnly(true);/*from w  w  w .  ja  v  a  2s .c  o m*/
    cookie.setMaxAge(expires);
    cookie.setPath("/");
    if (secured) {
        cookie.setSecure(true);
    }
    LOG.info(cookieAsString(cookie));
    httpServletResponse.addCookie(cookie);
}

From source file:net.e2.bw.idreg.client.keycloak.KeycloakClient.java

/** {@inheritDoc} */
public void redirectToAuthServer(HttpServletResponse response, String callbackUrl) throws IOException {

    // Create a state code used for Cross-Site Request Forgery (CSRF, XSRF) prevention
    String state = OIDCUtils.getStateCode();

    // Set up cookie used for Cross-Site Request Forgery (CSRF, XSRF) prevention
    Cookie cookie = new Cookie(OAUTH_TOKEN_REQUEST_STATE, state);
    //cookie.setSecure(isSecure);
    cookie.setPath("/");
    response.addCookie(cookie);/*from   ww  w  . ja va2  s  .c  om*/

    // Redirect to the authentication request
    String url = config.getAuthRequest(callbackUrl, state);
    log.log(Level.FINE, "Redirecting to auth request: " + url);
    response.sendRedirect(url);
}

From source file:com.stormcloud.ide.api.filter.UserFilter.java

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

    try {/* w  w w .  j a v  a  2  s  .c om*/

        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;

        LOG.info("Filter Request [" + request.getRemoteAddr() + "]");

        MDC.put("api", httpRequest.getRequestURI());

        if (httpRequest.getRequestURI().endsWith("/api/login")) {

            // configure MDC for the remainging trip
            MDC.put("userName", httpRequest.getRemoteUser());

            LOG.debug("Login Request.");

            // it's a login request which succeeded (Basic Auth)
            // so we now need to genereate an authentication token
            // and store it in a cookie we sent back
            // create the cookie with key for consecutive Rest API Calls

            // Get user from db and add to the localthread
            User user = dao.getUser(httpRequest.getRemoteUser());

            if (user == null) {

                LOG.error("User not found.");
                httpResponse.sendError(HttpStatus.FORBIDDEN.value());
                httpResponse.flushBuffer();
                return;
            }

            // update last login
            user.setLastLogin(Calendar.getInstance().getTime());

            dao.save(user);

            RemoteUser.set(user);

            try {

                // set the key cookie
                Cookie keyCookie = new Cookie("stormcloud-key", createKey(user, httpRequest.getRemoteAddr()));

                keyCookie.setMaxAge(60 * 60 * 24); // 1 day

                keyCookie.setPath("/");
                keyCookie.setSecure(true);

                httpResponse.addCookie(keyCookie);

                // set the username cookie
                Cookie userCookie = new Cookie("stormcloud-user", user.getUserName());

                userCookie.setMaxAge(60 * 60 * 24); // 1 day

                userCookie.setPath("/");
                userCookie.setSecure(true);

                httpResponse.addCookie(userCookie);

            } catch (NoSuchAlgorithmException e) {

                LOG.error(e);

                try {

                    // no go
                    httpResponse.sendError(HttpStatus.INTERNAL_SERVER_ERROR.value());

                    httpResponse.flushBuffer();
                    return;

                } catch (IOException ioe) {
                    LOG.error(ioe);
                }
            }

        } else if (httpRequest.getRequestURI().endsWith("/api/user/createAccount")) {

            // intercept and do something with create account
            LOG.debug("Create Account Request.");

        } else {

            LOG.info("API Request.");

            // any other request than a login
            // we need to check the username and received key
            Cookie[] cookies = httpRequest.getCookies();

            String userName = null;
            String key = null;

            if (cookies != null) {

                LOG.info("Found " + cookies.length + " Cookies");

                // loop trough the cookies
                for (int i = 0; i < cookies.length; i++) {

                    if (cookies[i].getName().equals("stormcloud-user")) {

                        LOG.debug("userName = " + cookies[i].getValue());
                        userName = cookies[i].getValue();
                    }

                    if (cookies[i].getName().equals("stormcloud-key")) {

                        LOG.debug("key = " + cookies[i].getValue());
                        key = cookies[i].getValue();
                    }
                }
            }

            if (userName == null || key == null) {

                LOG.info("Required credentials not found.");
                httpResponse.sendError(HttpStatus.FORBIDDEN.value());
                httpResponse.flushBuffer();
                return;

            } else {

                // configure MDC for the remainging trip
                MDC.put("userName", userName);

                // get user
                LOG.debug("Get Persisted User");
                User user = dao.getUser(userName);

                if (user == null) {
                    httpResponse.sendError(HttpStatus.FORBIDDEN.value());
                    httpResponse.flushBuffer();
                    return;
                }

                RemoteUser.set(user);

                try {

                    String matchKey = createKey(user, httpRequest.getRemoteAddr());

                    LOG.info("Validating Key.");

                    if (!matchKey.equals(key)) {

                        LOG.warn("Invalid Key!");
                        httpResponse.sendError(HttpStatus.FORBIDDEN.value());
                        httpResponse.flushBuffer();
                        return;

                    } else {

                        LOG.info("Request Authenticated");
                    }

                } catch (NoSuchAlgorithmException e) {

                    LOG.error(e);

                    try {

                        // no go
                        httpResponse.sendError(HttpStatus.INTERNAL_SERVER_ERROR.value());
                        httpResponse.flushBuffer();
                        return;

                    } catch (IOException ioe) {
                        LOG.error(ioe);
                    }
                }

            }
        }

        chain.doFilter(request, response);

    } catch (IOException e) {
        LOG.error(e);
    } catch (ServletException e) {
        LOG.error(e);
    } finally {

        // clear the logging diagnostics context
        MDC.clear();

        // Remove the user from memoty
        RemoteUser.destroy();
    }
}

From source file:eu.semlibproject.annotationserver.managers.CookiesManager.java

/**
 * Generate a new cookie for the annotation server
 * //  w ww .  j  a  v  a  2s .c  o  m
 * @param accessToken   the accessToken
 * @return              the new generated cookie
 */
public Cookie generateNewASCookie(String accessToken) {

    if (accessToken != null) {
        Cookie cookie = new Cookie(SemlibConstants.COOCKIE_NAME, accessToken);
        cookie.setComment(SemlibConstants.COOCKIE_DESCRIPTION);
        cookie.setPath(SemlibConstants.COOKIE_PATH);
        cookie.setMaxAge(SemlibConstants.COOKIE_TIME);
        cookie.setVersion(1);
        cookie.setSecure(false);

        return cookie;
    }

    return null;
}

From source file:net.shopxx.util.CookieUtils.java

/**
 * cookie/*from www.jav  a 2 s .  com*/
 * 
 * @param request
 *            HttpServletRequest
 * @param response
 *            HttpServletResponse
 * @param name
 *            cookie??
 * @param path
 *            
 * @param domain
 *            
 */
public static void removeCookie(HttpServletRequest request, HttpServletResponse response, String name,
        String path, String domain) {
    Assert.notNull(request);
    Assert.notNull(response);
    Assert.hasText(name);
    Cookie cookie = new Cookie(name, null);
    cookie.setMaxAge(0);
    if (StringUtils.isNotEmpty(path)) {
        cookie.setPath(path);
    }
    if (StringUtils.isNotEmpty(domain)) {
        cookie.setDomain(domain);
    }
    response.addCookie(cookie);
}

From source file:fi.helsinki.opintoni.security.CustomAuthenticationSuccessHandler.java

private void addHasLoggedInCookie(HttpServletResponse response) {
    Cookie cookie = new Cookie(Constants.OPINTONI_HAS_LOGGED_IN, Boolean.TRUE.toString());
    cookie.setMaxAge(Integer.MAX_VALUE);
    addCookie(response, cookie);/*w  ww. j  av  a  2s .  c o  m*/
}

From source file:io.seldon.api.controller.JsPortholeController.java

/**
 *
 * @param request .../*from   w ww  . j a  va2 s.co m*/
 * @param response ...
 * @param localId if non-null, use this local id instead of generating a {@link UUID}.
 *                Typically this will be used to propagate client-specific cookies where browser privacy issues have
 *                blocked the server-side setting.
 * @return
 */
private String ensureCookie(HttpServletRequest request, HttpServletResponse response, String localId) {
    final Cookie[] cookies = request.getCookies();
    String uuid = null;
    if (cookies != null) {
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals(RL_COOKIE_ID)) {
                uuid = cookie.getValue();
            }
        }
    }
    if (uuid == null) {
        if (localId != null) {
            logger.info("Using local ID for porthole session: " + localId);
            uuid = localId;
        } else {
            uuid = UUID.randomUUID().toString();
        }
        final Cookie cookie = new Cookie(RL_COOKIE_ID, uuid);
        cookie.setMaxAge(COOKIE_MAX_AGE);
        response.addCookie(cookie);
        response.addHeader("P3P", "CP=\"IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT\"");
    }
    return uuid;
}