Example usage for javax.servlet.http HttpServletResponse addCookie

List of usage examples for javax.servlet.http HttpServletResponse addCookie

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletResponse addCookie.

Prototype

public void addCookie(Cookie cookie);

Source Link

Document

Adds the specified cookie to the response.

Usage

From source file:org.alfresco.web.app.servlet.AuthenticationHelper.java

/**
 * Setup the Alfresco auth cookie value.
 * //from  w  w  w  .  j  a  v a2  s  .  c om
 * @param httpRequest
 * @param httpResponse
 * @param username
 */
public static void setUsernameCookie(HttpServletRequest httpRequest, HttpServletResponse httpResponse,
        String username) {
    if (logger.isDebugEnabled())
        logger.debug("Setting up the Alfresco auth cookie for " + username);
    Cookie authCookie = getAuthCookie(httpRequest);
    // Let's Base 64 encode the username so it is a legal cookie value
    String encodedUsername;
    try {
        encodedUsername = Base64.encodeBytes(username.getBytes("UTF-8"));
        if (logger.isDebugEnabled())
            logger.debug("Base 64 encode the username: " + encodedUsername);
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e);
    }
    if (authCookie == null) {
        if (logger.isDebugEnabled())
            logger.debug("No Alfresco auth cookie wa found, creating new one.");
        authCookie = new Cookie(COOKIE_ALFUSER, encodedUsername);
    } else {
        if (logger.isDebugEnabled())
            logger.debug("Updating the previous Alfresco auth cookie value.");
        authCookie.setValue(encodedUsername);
    }
    authCookie.setPath(httpRequest.getContextPath());
    // TODO: make this configurable - currently 7 days (value in seconds)
    authCookie.setMaxAge(60 * 60 * 24 * 7);
    httpResponse.addCookie(authCookie);
}

From source file:SettingandReadingCookies.java

public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();

    out.println("<HTML>");
    out.println("<HEAD>");
    out.println("<TITLE>");
    out.println("A Web Page");
    out.println("</TITLE>");
    out.println("</HEAD>");
    out.println("<BODY");

    Cookie[] cookies = request.getCookies();
    boolean foundCookie = false;

    for (int loopIndex = 0; loopIndex < cookies.length; loopIndex++) {
        Cookie cookie1 = cookies[loopIndex];
        if (cookie1.getName().equals("color")) {
            out.println("bgcolor = " + cookie1.getValue());
            foundCookie = true;/*from  w  w w  . ja  va  2s . com*/
        }
    }

    if (!foundCookie) {
        Cookie cookie1 = new Cookie("color", "cyan");
        cookie1.setMaxAge(24 * 60 * 60);
        response.addCookie(cookie1);
    }

    out.println(">");
    out.println("<H1>Setting and Reading Cookies</H1>");
    out.println("This page will set its background color using a cookie when reloaded.");
    out.println("</BODY>");
    out.println("</HTML>");
}

From source file:CookieServlet.java

public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, java.io.IOException {

    Cookie cookie = null;/*from   w  ww  .j a  va 2  s .co m*/
    Cookie[] cookies = request.getCookies();
    boolean newCookie = false;

    if (cookies != null) {
        for (int i = 0; i < cookies.length; i++) {
            if (cookies[i].getName().equals("mycookie")) {
                cookie = cookies[i];
            }
        }
    }
    if (cookie == null) {
        newCookie = true;
        int maxAge;
        try {
            maxAge = new Integer(getServletContext().getInitParameter("cookie-age")).intValue();
        } catch (Exception e) {
            maxAge = -1;
        }

        cookie = new Cookie("mycookie", "" + getNextCookieValue());
        cookie.setPath(request.getContextPath());
        cookie.setMaxAge(maxAge);
        response.addCookie(cookie);
    }
    response.setContentType("text/html");
    java.io.PrintWriter out = response.getWriter();

    out.println("<html>");
    out.println("<head>");
    out.println("<title>Cookie info</title>");
    out.println("</head>");
    out.println("<body>");

    out.println("<h2> Information about the cookie named \"mycookie\"</h2>");

    out.println("Cookie value: " + cookie.getValue() + "<br>");
    if (newCookie) {
        out.println("Cookie Max-Age: " + cookie.getMaxAge() + "<br>");
        out.println("Cookie Path: " + cookie.getPath() + "<br>");
    }

    out.println("</body>");
    out.println("</html>");

    out.close();
}

From source file:org.apache.archiva.redback.integration.util.AutoLoginCookies.java

public void setRememberMeCookie(String principal, HttpServletResponse httpServletResponse,
        HttpServletRequest httpServletRequest) {
    if (!isRememberMeEnabled()) {
        return;/* w  w w  .j  a  va  2 s .  co m*/
    }

    try {
        CookieSettings settings = securitySystem.getPolicy().getRememberMeCookieSettings();
        int timeout = settings.getCookieTimeout();
        KeyManager keyManager = securitySystem.getKeyManager();
        AuthenticationKey authkey = keyManager.createKey(principal, "Remember Me Key", timeout);

        Cookie cookie = createCookie(REMEMBER_ME_KEY, authkey.getKey(), settings.getDomain(),
                settings.getPath(), httpServletRequest);
        if (timeout > 0) {
            cookie.setMaxAge(timeout);
        }
        httpServletResponse.addCookie(cookie);

    } catch (KeyManagerException e) {
        log.warn("Unable to set remember me cookie.");
    }
}

From source file:hudson.Functions.java

/**
 * Used by <tt>layout.jelly</tt> to control the auto refresh behavior.
 *
 * @param noAutoRefresh/*from w  w w  .j  a va 2 s.c o  m*/
 *      On certain pages, like a page with forms, will have annoying interference
 *      with auto refresh. On those pages, disable auto-refresh.
 */
public static void configureAutoRefresh(HttpServletRequest request, HttpServletResponse response,
        boolean noAutoRefresh) {
    if (noAutoRefresh)
        return;

    String param = request.getParameter("auto_refresh");
    boolean refresh = isAutoRefresh(request);
    if (param != null) {
        refresh = Boolean.parseBoolean(param);
        Cookie c = new Cookie("hudson_auto_refresh", Boolean.toString(refresh));
        // Need to set path or it will not stick from e.g. a project page to the dashboard.
        // Using request.getContextPath() might work but it seems simpler to just use the hudson_ prefix
        // to avoid conflicts with any other web apps that might be on the same machine.
        c.setPath("/");
        c.setMaxAge(60 * 60 * 24 * 30); // persist it roughly for a month
        response.addCookie(c);
    }
    if (refresh) {
        response.addHeader("Refresh", "10");
    }
}

From source file:de.escidoc.core.aa.servlet.Login.java

/**
 * Sends the response in case of successfully authenticating the user.<br> The provided handle that identifies the
 * user in the system is sent back in the {@code Authorization} header (to be used by the redirecting
 * application) and via a cookie to enable handling of later calls to the servlet of the same user and to enable
 * direct accesses of the user to the framework by using a web browser.
 *
 * @param request  The http request.//from   w w w  .j  av  a2s  .com
 * @param response The http response.
 * @param handle   The handle identifying the user.
 * @throws IOException              Thrown in case of an error.
 * @throws WebserverSystemException Thrown in case of an internal error.
 */
private void sendAuthenticated(final HttpServletRequest request, final HttpServletResponse response,
        final String handle) throws IOException, WebserverSystemException {

    response.reset();

    // add escidoc cookie
    response.addCookie(UserHandleCookieUtil.createAuthCookie(handle));

    // FIXME: should method return null instead of exception?
    String redirectUrlWithHandle;
    try {
        redirectUrlWithHandle = createRedirectUrl(request, handle);
    } catch (final MissingParameterException e) {
        if (LOGGER.isWarnEnabled()) {
            LOGGER.warn("Error on creating redirect URL.");
        }
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Error on creating redirect URL.", e);
        }
        redirectUrlWithHandle = null;
    }

    if (redirectUrlWithHandle == null) {
        sendResponse(response, getAuthenticatedPage(null));
    } else {
        sendRedirectingResponse(response, getAuthenticatedPage(redirectUrlWithHandle), redirectUrlWithHandle);
    }
}

From source file:com.traffitruck.web.HtmlController.java

private void setSessionCookie(HttpServletResponse response, String regid, int expiry) {
    Cookie cookie = new Cookie(DEVICE_REGISTRATION_COOKIE_NAME, regid);
    cookie.setMaxAge(expiry);//from w  ww .  j ava  2s  . com
    cookie.setHttpOnly(true);
    // cookie.setSecure(true);
    response.addCookie(cookie);
}

From source file:de.appsolve.padelcampus.utils.LoginUtil.java

public void updateLoginCookie(HttpServletRequest request, HttpServletResponse response) {
    Player player = sessionUtil.getUser(request);
    if (player != null) {
        UUID cookieUUID = UUID.randomUUID();
        UUID cookieValue = UUID.randomUUID();
        String cookieValueHash = BCrypt.hashpw(cookieValue.toString(), BCrypt.gensalt());
        LoginCookie loginCookie = new LoginCookie();
        loginCookie.setUUID(cookieUUID.toString());
        loginCookie.setPlayerUUID(player.getUUID());
        loginCookie.setLoginCookieHash(cookieValueHash);
        loginCookie.setValidUntil(new LocalDate().plusYears(1));
        loginCookieDAO.saveOrUpdate(loginCookie);
        Cookie cookie = new Cookie(COOKIE_LOGIN_TOKEN, cookieUUID.toString() + ":" + cookieValue.toString());
        cookie.setDomain(request.getServerName());
        cookie.setMaxAge(ONE_YEAR_SECONDS);
        cookie.setPath("/");
        response.addCookie(cookie);
    }/* w w w.  ja v a 2s .co  m*/
}

From source file:com.jolira.testing.CachingRESTProxy.java

private boolean handleCachedResponse(final File query, final HttpServletResponse response) throws IOException {
    final CachedResponse cached = getCached(query);

    if (cached == null) {
        return false;
    }/*ww  w . j a  v  a 2  s  . c  o m*/

    final int status = cached.getStatus();
    final String mimeType = cached.getContentType();
    final File resource = cached.getResource();
    final Cookie[] cookies = cached.getCookies();

    if (cookies != null) {
        for (final Cookie cookie : cookies) {
            response.addCookie(cookie);
        }
    }
    response.setStatus(status);
    respond(mimeType, response, resource);

    return true;
}

From source file:com.microsoft.azure.oidc.filter.helper.impl.SimpleAuthenticationHelper.java

private String addCookie(final HttpServletRequest httpRequest, final HttpServletResponse httpResponse,
        final String cookieName, final String cookieValue) {
    if (httpRequest == null || httpResponse == null || cookieName == null || cookieValue == null) {
        throw new PreconditionException("Required parameter is null");
    }/*from   w  ww .  j a va2  s.c  o  m*/
    final Cookie cookie = new Cookie(cookieName, "");
    cookie.setValue(cookieValue);
    cookie.setMaxAge(-1);
    cookie.setSecure(true);
    cookie.setDomain(httpRequest.getServerName());
    cookie.setPath("/");
    cookie.setHttpOnly(true);
    httpResponse.addCookie(cookie);
    return cookie.getValue();
}