Example usage for javax.servlet.http Cookie setValue

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

Introduction

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

Prototype

public void setValue(String newValue) 

Source Link

Document

Assigns a new value to this Cookie.

Usage

From source file:ro.nextreports.server.web.integration.IntegrationAuthenticationFilter.java

private void removeJSessionIdCookie(HttpServletRequest request, HttpServletResponse response) {
    Cookie[] cookies = request.getCookies();
    //      System.out.println("cookies = " + cookies);
    if (cookies != null) {
        for (Cookie cookie : cookies) {
            //              System.out.println("..... cookie: " + cookie);
            if ("JSESSIONID".equals(cookie.getName())) {
                //                 System.out.println("==> remove jsessionid cookie with value " + cookie.getValue());
                if (logger.isDebugEnabled()) {
                    logger.debug("remove jsessionid cookie with value " + cookie.getValue());
                }//from w ww . ja  v a 2 s .co  m
                cookie.setValue("");
                //                 cookie.setPath("/");
                cookie.setMaxAge(0);
                response.addCookie(cookie);
            }
        }
    }
}

From source file:com.salesmanager.catalog.CatalogInterceptor.java

@Override
protected String doIntercept(ActionInvocation invoke, HttpServletRequest req, HttpServletResponse resp)
        throws Exception {

    /** remove profile url **/
    req.getSession().removeAttribute("profileUrl");

    /** synchronize mini shopping cart**/

    //get http session shopping cart
    ShoppingCart cart = SessionUtil.getMiniShoppingCart(req);
    MerchantStore mStore = SessionUtil.getMerchantStore(req);

    if (cart == null) {//synch only when the cart is null or empty

        Cookie[] cookies = req.getCookies();
        if (cookies != null) {
            for (int i = 0; i < cookies.length; i++) {
                Cookie cookie = cookies[i];
                if (cookie.getName().equals(CatalogConstants.SKU_COOKIE + mStore.getMerchantId())) {

                    Locale locale = LocaleUtil.getLocale(req);

                    String cookieValue = StringUtil.unescape(cookie.getValue());

                    ShoppingCart sc = MiniShoppingCartSerializationUtil.deserializeJSON(cookieValue, mStore,
                            locale);//from   w  w w .  j  a  v a2s .  c o m
                    if (sc != null) {

                        MiniShoppingCartUtil.calculateTotal(sc, mStore);
                        SessionUtil.setMiniShoppingCart(sc, req);

                    } else {//expire cookie
                        cookie.setValue(null);
                        cookie.setMaxAge(0);
                        resp.addCookie(cookie);
                    }
                }
            }
        }

    }

    return null;

}

From source file:org.akaza.openclinica.control.MainMenuServlet.java

public String getQueryStrCookie(HttpServletRequest request, HttpServletResponse response) {
    String queryStr = "";
    Cookie[] cookies = request.getCookies();
    for (Cookie cookie : cookies) {
        if (cookie.getName().equalsIgnoreCase("queryStr")) {
            try {
                queryStr = URLDecoder.decode(cookie.getValue(), "UTF-8");
            } catch (UnsupportedEncodingException e) {
                logger.error("Error decoding redirect URL from queryStr cookie:" + e.getMessage());
            }//  w w  w.  ja  v a 2  s . c o m
            cookie.setValue(null);
            cookie.setMaxAge(0);
            cookie.setPath("/");
            if (response != null)
                response.addCookie(cookie);
            break;
        }
    }
    return queryStr;
}

From source file:org.akaza.openclinica.control.MainMenuServlet.java

public String getTimeoutReturnToCookie(HttpServletRequest request, HttpServletResponse response) {
    String queryStr = "";
    if (ub == null || StringUtils.isEmpty(ub.getName()))
        return queryStr;

    Cookie[] cookies = request.getCookies();
    for (Cookie cookie : cookies) {
        if (cookie.getName().equalsIgnoreCase("bridgeTimeoutReturn-" + ub.getName())) {
            try {
                queryStr = URLDecoder.decode(cookie.getValue(), "UTF-8");
            } catch (UnsupportedEncodingException e) {
                logger.error("Error decoding redirect URL from queryStr cookie:" + e.getMessage());
            }//from  w  w w  . j av a  2  s . co m
            cookie.setValue(null);
            cookie.setMaxAge(0);
            cookie.setPath("/");
            if (response != null)
                response.addCookie(cookie);
            break;
        }
    }
    return queryStr;
}

From source file:org.syncope.console.commons.PreferenceManager.java

public void set(final Request request, final Response response, final Map<String, List<String>> prefs) {

    Cookie prefCookie = ((WebRequest) request).getCookie(Constants.PREFS_COOKIE_NAME);

    final Map<String, String> current = new HashMap<String, String>();

    if (prefCookie == null || !StringUtils.hasText(prefCookie.getValue())) {
        prefCookie = new Cookie(Constants.PREFS_COOKIE_NAME, null);
    } else {//w ww  .  j a v a2 s .com
        current.putAll(getPrefs(new String(Base64.decodeBase64(prefCookie.getValue().getBytes()))));
    }

    // after retrieved previous setting in order to overwrite the key ...
    for (Entry<String, List<String>> entry : prefs.entrySet()) {
        current.put(entry.getKey(), StringUtils.collectionToDelimitedString(entry.getValue(), ";"));
    }

    try {
        prefCookie.setValue(new String(Base64.encodeBase64(setPrefs(current).getBytes())));
    } catch (IOException e) {
        LOG.error("Could not set preferences " + current, e);
    }

    prefCookie.setMaxAge(ONE_YEAR_TIME);
    ((WebResponse) response).addCookie(prefCookie);
}

From source file:uk.ac.ed.epcc.webapp.servlet.DefaultServletService.java

/**invalidate the servlet session and optionally remove the session cookie.
 *
 * /*from   w w  w  . ja va2  s  . com*/
 * 
 * @param remove_cookie should cookie be removed
 * 
 */
public void logout(boolean remove_cookie) {
    HttpSession sess = getSession();
    if (sess != null) {
        sess.invalidate();
    }
    if (remove_cookie) {
        HttpServletRequest request = getRequest();
        if (request != null) {
            Cookie[] cookies = request.getCookies();
            if (cookies != null && cookies.length > 0) {
                for (Cookie c : cookies) {
                    if (c.getName().equalsIgnoreCase("JSESSIONID") || getContext()
                            .getBooleanParameter(LOGOUT_REMOVE_COOKIE_PREFIX + c.getName(), false)) {
                        Cookie c2 = (Cookie) c.clone();
                        c2.setMaxAge(0); // This should request a delete
                        if (c2.getPath() == null) {
                            String contextPath = request.getContextPath();
                            c2.setPath(contextPath + "/"); // browser did not include path. This will only work if path matched exactly
                        }
                        c2.setValue("");
                        ((HttpServletResponse) res).addCookie(c2);
                    }
                }
            }
        }
    }
}

From source file:com.google.gsa.valve.modules.httpbasic.HTTPBasicAuthenticationProcess.java

/**
 * This is the main method that does the authentication and should be 
 * invoked by the classes that would like to open a new authentication 
 * process against an HTTP Basic protected source.
 * <p>//  w ww  .  j  a  v  a 2 s. c  o m
 * The username and password for the source are assumed to be the ones 
 * captured during the authentication. These are stored in creds and in 
 * this case the root parameters. creds is an array of credentials for 
 * all external sources. The first element is 'root' which contains the 
 * credentials captured from the login page. This method reviews if there 
 * is a credential id identical to the name associated to this module 
 * in the config file. If so, these credentials are used to authenticate 
 * against this HTTP Basic source, and if not 'root' one will be used 
 * instead.
 * <p>
 * If the HTTP Basic authentication result is OK, it creates an 
 * authentication cookie containing the HTTP Basic credentials 
 * to be reused during authorization. The content returned back from the 
 * remote secure backend system is sent as well. Anyway, the HTTP 
 * response code is returned in this method to inform the caller on the 
 * status.
 * 
 * @param request HTTP request
 * @param response HTTP response
 * @param authCookies vector that contains the authentication cookies
 * @param url the document url
 * @param creds an array of credentials for all external sources
 * @param id the default credential id to be retrieved from creds
        
 * @return the HTTP error code
        
 * @throws HttpException
 * @throws IOException
 */
public int authenticate(HttpServletRequest request, HttpServletResponse response, Vector<Cookie> authCookies,
        String url, Credentials creds, String id) throws HttpException, IOException {

    Cookie[] cookies = null;

    //Credentials                     
    UsernamePasswordCredentials credentials = null;

    // Initialize status code
    int statusCode = HttpServletResponse.SC_UNAUTHORIZED;

    // Read cookies
    cookies = request.getCookies();

    // Debug
    logger.debug("HTTP Basic authentication start");

    //First read the u/p the credentails store, in this case using the same as the root login
    logger.debug("HttpBasic: trying to get creds from repository ID: " + id);
    Credential httpBasicCred = null;
    try {
        httpBasicCred = creds.getCredential(id);
    } catch (NullPointerException npe) {
        logger.error("NPE while reading credentials of ID: " + id);
    }
    if (httpBasicCred != null) {
        credentials = new UsernamePasswordCredentials(httpBasicCred.getUsername(), httpBasicCred.getPassword());
    } else {
        logger.debug("HttpBasic: trying to get creds from repository \"root\"");
        httpBasicCred = creds.getCredential("root");
        if (httpBasicCred != null) {
            logger.info("Trying with root credentails");
            credentials = new UsernamePasswordCredentials(httpBasicCred.getUsername(),
                    httpBasicCred.getPassword());
        }
    }

    logger.debug("Authenticating");
    Header[] headers = null;
    HttpMethodBase method = null;

    //Get Max connections
    int maxConnectionsPerHost = 30;
    int maxTotalConnections = 100;

    //Cookie Max Age
    int authMaxAge = -1;

    try {
        maxConnectionsPerHost = new Integer(valveConf.getMaxConnectionsPerHost()).intValue();
        maxTotalConnections = (new Integer(valveConf.getMaxTotalConnections())).intValue();
        authMaxAge = Integer.parseInt(valveConf.getAuthMaxAge());
    } catch (NumberFormatException nfe) {
        logger.error(
                "Configuration error: chack the configuration file as the numbers set for any of the following parameters are not OK:");
        logger.error("  * maxConnectionsPerHost    * maxTotalConnections    * authMaxAge");
    }

    // Protection
    if (webProcessor == null) {
        // Instantiate Web processor
        if ((maxConnectionsPerHost != -1) && (maxTotalConnections != -1)) {
            webProcessor = new WebProcessor(maxConnectionsPerHost, maxTotalConnections);
        } else {
            webProcessor = new WebProcessor();
        }
    }

    //
    // Launch the authentication process
    //

    // A fixed URL in the repository that all users have access to which can be used to authN a user
    // and capture the HTTP Authorization Header
    String authURL = valveConf.getRepository(id).getParameterValue("HTTPAuthPage");

    try {

        // Set HTTP headers
        headers = new Header[1];

        // Set User-Agent
        headers[0] = new Header("User-Agent",
                "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8) Gecko/20051111 Firefox/1.5");

        // Request page, testing if credentials are valid
        if (credentials != null) {
            logger.debug("Username: " + credentials.getUserName());
            logger.debug("URL: " + authURL);
        }

        //HTTP request
        method = webProcessor.sendRequest(credentials, RequestType.GET_REQUEST, headers, null, authURL);

        //Read the auth header and store in the cookie, the authZ class will use this later
        headers = method.getRequestHeaders();

        Header authHeader = null;
        authHeader = method.getRequestHeader("Authorization");

        // Cache status code
        if (method != null)
            statusCode = method.getStatusCode();

        if (statusCode == HttpServletResponse.SC_OK) {
            //Authentication worked, so create the auth cookie to indicate it has worked
            Cookie extAuthCookie = null;
            extAuthCookie = new Cookie(BASIC_COOKIE, "");

            if (authHeader != null) {

                String basicCookie = null;

                try {
                    basicCookie = URLEncoder.encode(getBasicAuthNChain(authHeader.getValue()), encoder);
                    if (basicCookie == null) {
                        basicCookie = "";
                    }
                } catch (Exception ex) {
                    logger.error("Error when setting Basic cookie value: " + ex.getMessage(), ex);
                    basicCookie = "";
                }

                extAuthCookie.setValue(basicCookie);

            }
            String authCookieDomain = null;
            String authCookiePath = null;

            // Cache cookie properties
            authCookieDomain = valveConf.getAuthCookieDomain();
            authCookiePath = valveConf.getAuthCookiePath();

            // Set extra cookie parameters
            extAuthCookie.setDomain(authCookieDomain);
            extAuthCookie.setPath(authCookiePath);
            extAuthCookie.setMaxAge(authMaxAge);

            // Log info
            if (logger.isDebugEnabled())
                logger.debug("Adding " + BASIC_COOKIE + " cookie: " + extAuthCookie.getName() + ":"
                        + extAuthCookie.getValue() + ":" + extAuthCookie.getPath() + ":"
                        + extAuthCookie.getDomain() + ":" + extAuthCookie.getSecure());

            //sendCookies support                        
            boolean isSessionEnabled = new Boolean(valveConf.getSessionConfig().isSessionEnabled())
                    .booleanValue();
            boolean sendCookies = false;
            if (isSessionEnabled) {
                sendCookies = new Boolean(valveConf.getSessionConfig().getSendCookies()).booleanValue();
            }
            if ((!isSessionEnabled) || ((isSessionEnabled) && (sendCookies))) {
                logger.debug("Adding cookie to response");
                response.addCookie(extAuthCookie);
            }

            //Add cookies to the Cookie array to support sessions
            authCookies.add(extAuthCookie);
            logger.debug("Cookie added to the array");

        }

        // Clear webProcessor cookies
        webProcessor.clearCookies();

    } catch (Exception e) {

        // Log error
        logger.error("HTTP Basic authentication failure: " + e.getMessage(), e);

        // Garbagge collect
        method = null;

        // Update status code
        statusCode = HttpServletResponse.SC_UNAUTHORIZED;

    }

    // End of the authentication process
    logger.debug("HTTP Basic Authentication completed (" + statusCode + ")");

    // Return status code
    return statusCode;

}

From source file:org.sakaiproject.gradebook.gwt.server.WebAppToolServlet.java

protected void service(final HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    // GRBK-908/*from  w w w . ja  v  a  2 s .  c  o  m*/
    if (null == sessionManager) {

        log.error("ERROR: SessionManager is null");
    } else {

        String currentSessionId = sessionManager.getCurrentSession().getId();
        String currentToken = (String) sessionManager.getCurrentSession().getAttribute(AppConstants.GB2_TOKEN);
        Cookie cookie = getCookie(request.getCookies());

        /*
         *  Creating a new GB2 TOKEN if:
         *  1: During bootstrapping time, fist access
         *  2: User deleted cookies
         */
        if (((null == currentToken || "".equals(currentToken)) && null != currentSessionId)
                || (null == cookie && null != currentSessionId)) {

            String hexCurrentSessionId = DigestUtils.md5Hex(currentSessionId.getBytes());

            String uuid = java.util.UUID.randomUUID().toString();
            String gb2Token = new StringBuilder(uuid).append("-").append(hexCurrentSessionId).toString();

            sessionManager.getCurrentSession().setAttribute(AppConstants.GB2_TOKEN, gb2Token);

            // If the cookie exists, we just change its value, otherwise we create a new one
            if (null != cookie) {

                cookie.setValue(gb2Token);
                cookie.setPath("/");
                cookie.setMaxAge(-1);
            } else {

                cookie = new Cookie(AppConstants.GB2_TOKEN, gb2Token);
                cookie.setPath("/");
                cookie.setMaxAge(-1);
            }

            response.addCookie(cookie);
        }
    }

    final String contextPath = request.getContextPath();
    request.setAttribute(Tool.NATIVE_URL, Tool.NATIVE_URL);
    HttpServletRequest wrappedRequest = new HttpServletRequestWrapper(request) {
        public String getContextPath() {
            return contextPath;
        }
    };

    if (request.getPathInfo() == null && getInitParameter(FIRST_PAGE) != null
            && !getInitParameter(FIRST_PAGE).equals("/")) {

        String uri = new StringBuilder().append(contextPath).append(getInitParameter(FIRST_PAGE)).toString();

        addVersionAsCookie(response, contextPath);
        // Set locale preferences for user
        uri = uri + "?locale=" + rb.getLocale();

        // Do redirect to first-page
        response.sendRedirect(uri);
    } else if (request.getPathInfo() == null && !request.getRequestURI().endsWith("/")) {
        String uri = new StringBuilder().append(contextPath).append("/").toString();

        // we should do the default redirect to "/"
        response.sendRedirect(uri);
    } else if (request.getPathInfo() != null
            && (request.getPathInfo().startsWith("/WEB-INF/") || request.getPathInfo().equals("/WEB-INF"))) {
        String uri = new StringBuilder().append(contextPath).append("/").toString();

        // Can't allow people to see WEB-INF
        response.sendRedirect(uri);
    } else {
        // otherwise do the dispatch
        RequestDispatcher dispatcher;
        if (request.getPathInfo() == null) {
            dispatcher = request.getRequestDispatcher("");
        } else {
            dispatcher = request.getRequestDispatcher(request.getPathInfo());
        }

        dispatcher.forward(wrappedRequest, response);
    }

}

From source file:org.opencms.workplace.CmsLogin.java

/**
 * Sets the login cookies.<p>//w w w.jav  a  2s  .c o m
 */
public void setCookieData() {

    // set the PC type cookie only if security dialog is enabled
    if (OpenCms.getLoginManager().isEnableSecurity() && CmsStringUtil.isNotEmpty(m_pcType)) {
        Cookie pcTypeCookie = getCookie(COOKIE_PCTYPE);
        pcTypeCookie.setValue(m_pcType);
        setCookie(pcTypeCookie, false);
    }

    // only store user name and OU cookies on private PC types
    if (PCTYPE_PRIVATE.equals(m_pcType)) {
        // set the user name cookie
        Cookie userNameCookie = getCookie(COOKIE_USERNAME);
        userNameCookie.setValue(m_username);
        setCookie(userNameCookie, false);

        // set the organizational unit cookie
        Cookie ouFqnCookie = getCookie(COOKIE_OUFQN);
        ouFqnCookie.setValue(m_oufqn);
        setCookie(ouFqnCookie, false);
    } else if (OpenCms.getLoginManager().isEnableSecurity() && PCTYPE_PUBLIC.equals(m_pcType)) {
        // delete user name and organizational unit cookies 
        Cookie userNameCookie = getCookie(COOKIE_USERNAME);
        setCookie(userNameCookie, true);
        Cookie ouFqnCookie = getCookie(COOKIE_OUFQN);
        setCookie(ouFqnCookie, true);

    }
}

From source file:com.kodemore.servlet.ScServletData.java

/**
 * The cookie should be a new instance that contains the correct
 * values for name, domain, and path./*from ww  w.j  a va  2  s .  c o  m*/
 */
public void _clearCookie(Cookie e) {
    e.setValue(REMOVED_COOKIE_VALUE);
    e.setMaxAge(0);
    _setCookie(e);
}