Example usage for javax.servlet.http Cookie getValue

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

Introduction

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

Prototype

public String getValue() 

Source Link

Document

Gets the current value of this Cookie.

Usage

From source file:com.ibm.jaggr.core.impl.transport.AbstractHttpTransport.java

/**
 * This method checks the request for the has conditions which may either be contained in URL
 * query arguments or in a cookie sent from the client.
 *
 * @param request//  w w  w . ja  v  a2  s.c o  m
 *            the request object
 * @return The has conditions from the request.
 * @throws IOException
 * @throws UnsupportedEncodingException
 */
protected String getHasConditionsFromRequest(HttpServletRequest request) throws IOException {

    final String sourceMethod = "getHasConditionsFromRequest"; //$NON-NLS-1$
    boolean isTraceLogging = log.isLoggable(Level.FINER);
    if (isTraceLogging) {
        log.entering(AbstractHttpTransport.class.getName(), sourceMethod, new Object[] { request });
    }
    String ret = null;
    if (request.getParameter(FEATUREMAPHASH_REQPARAM) != null) {
        // The cookie called 'has' contains the has conditions
        if (isTraceLogging) {
            log.finer("has hash = " + request.getParameter(FEATUREMAPHASH_REQPARAM)); //$NON-NLS-1$
        }
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (int i = 0; ret == null && i < cookies.length; i++) {
                Cookie cookie = cookies[i];
                if (cookie.getName().equals(FEATUREMAP_REQPARAM) && cookie.getValue() != null) {
                    if (isTraceLogging) {
                        log.finer("has cookie = " + cookie.getValue()); //$NON-NLS-1$
                    }
                    ret = URLDecoder.decode(cookie.getValue(), "US-ASCII"); //$NON-NLS-1$
                    break;
                }
            }
        }
        if (ret == null) {
            if (log.isLoggable(Level.WARNING)) {
                StringBuffer url = request.getRequestURL();
                if (url != null) { // might be null if using mock request for unit testing
                    url.append("?").append(request.getQueryString()).toString(); //$NON-NLS-1$
                    log.warning(MessageFormat.format(Messages.AbstractHttpTransport_0,
                            new Object[] { url, request.getHeader("User-Agent") })); //$NON-NLS-1$
                }
            }
        }
    } else {
        ret = request.getParameter(FEATUREMAP_REQPARAM);
        if (isTraceLogging) {
            log.finer("reading features from has query arg"); //$NON-NLS-1$
        }
    }
    if (isTraceLogging) {
        log.exiting(AbstractHttpTransport.class.getName(), sourceMethod, ret);
    }
    return ret;
}

From source file:com.google.gsa.valve.modules.noauth.HTTPNoAuthenticationProcess.java

/**
 * This method simulates the authentication process against a content 
 * source, so that every document is consider here as public.
 * <p>/*from w  w w .  j a v  a 2s  .c  om*/
 * Creates the authentication cookie and always return 200, unless there is 
 * any problem processing the request.
 * 
 * @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;

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

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

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

    //
    // Launch the authentication process
    //

    // Protection
    try {

        Cookie extAuthCookie = null;
        extAuthCookie = new Cookie("gsa_basic_noauth", "");

        extAuthCookie.setValue("true");

        String authCookieDomain = null;
        String authCookiePath = null;
        int authMaxAge = -1;

        // Cache cookie properties
        authCookieDomain = (request.getAttribute("authCookieDomain")).toString();
        authCookiePath = (request.getAttribute("authCookiePath")).toString();
        //authMaxAge
        try {
            authMaxAge = Integer.parseInt(valveConf.getAuthMaxAge());
        } catch (NumberFormatException nfe) {
            logger.error(
                    "Configuration error: chack the configuration file as the number set for authMaxAge is not OK:");
        }

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

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

        //add 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))) {
            response.addCookie(extAuthCookie);
        }

        //add cookie to the array
        authCookies.add(extAuthCookie);

        statusCode = HttpServletResponse.SC_OK;

    } catch (Exception e) {

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

        // Update status code
        statusCode = HttpServletResponse.SC_UNAUTHORIZED;

    }

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

    // Return status code
    return statusCode;

}

From source file:com.konakart.actions.BaseAction.java

/**
 * Utility method to get the CustomerUuid from the browser cookie and create the cookie if it
 * doesn't exist.//  w  ww .  j a  v a2s .  c o  m
 * 
 * @param request
 * @return Returns the CustomerUuid
 */
private String getCustomerUuidFromBrowserCookie(HttpServletRequest request, HttpServletResponse response) {
    /*
     * Try to find the cookie we are looking for
     */
    Cookie[] cookies = request.getCookies();
    String uuid = null;
    if (cookies != null) {
        for (int i = 0; i < cookies.length; i++) {
            Cookie cookie = cookies[i];
            String cookieName = cookie.getName();
            if (cookieName.equals(CUSTOMER_UUID)) {
                /*
                 * If we find the cookie we get the value and update the max age.
                 */
                uuid = cookie.getValue();
                cookie.setMaxAge(COOKIE_MAX_AGE_IN_SECS);
                cookie.setPath("/");
                response.addCookie(cookie);
            }
        }
    }

    /*
     * If the browser cookie doesn't exist then we have to create it and store a newly created
     * UUID string
     */
    if (uuid == null) {
        UUID uuidObject = UUID.randomUUID();
        uuid = uuidObject.toString();
        /*
         * Create a browser cookie with the UUID
         */
        Cookie uuidCookie = new Cookie(CUSTOMER_UUID, uuid);
        uuidCookie.setMaxAge(COOKIE_MAX_AGE_IN_SECS);
        uuidCookie.setPath("/");
        response.addCookie(uuidCookie);
    }

    return uuid;
}

From source file:org.workcast.ssoficlient.service.LoginHandler.java

/**
 * Returns the value of a named cookie if there is one, returns null if
 * there is not/*from  w w  w  .j a v  a  2s  .  c  om*/
 */
public String findTenantCookieValue(String cookieName) throws Exception {
    // make a tenant-specific cookie name automatically
    if (aa != null && aa.tenant != null) {
        cookieName = cookieName + URLEncoder.encode(aa.tenant, "UTF-8");
    }
    Cookie[] cookies = request.getCookies();
    if (cookies != null) {
        for (Cookie oneCookie : cookies) {
            if (oneCookie != null) {
                String cName = oneCookie.getName();
                if (cName != null && cookieName.equals(cName)) {
                    return oneCookie.getValue();
                }
            }
        }
    }
    return "";
}

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

/** Format a set cookie value
 * @param cookie The cookie.//from   w  w w . j a v  a 2  s.c  o m
 */
public void addSetCookie(Cookie cookie) {
    String name = cookie.getName();
    String value = cookie.getValue();
    int version = cookie.getVersion();

    // Check arguments
    if (name == null || name.length() == 0)
        throw new IllegalArgumentException("Bad cookie name");

    // Format value and params
    StringBuffer buf = new StringBuffer(128);
    String name_value_params = null;
    synchronized (buf) {
        buf.append(name);
        buf.append('=');
        if (value != null && value.length() > 0) {
            if (version == 0)
                URI.encodeString(buf, value, "\";, '");
            else
                buf.append(QuotedStringTokenizer.quote(value, "\";, '"));
        }

        if (version > 0) {
            buf.append(";Version=");
            buf.append(version);
            String comment = cookie.getComment();
            if (comment != null && comment.length() > 0) {
                buf.append(";Comment=");
                QuotedStringTokenizer.quote(buf, comment);
            }
        }
        String path = cookie.getPath();
        if (path != null && path.length() > 0) {
            buf.append(";Path=");
            buf.append(path);
        }
        String domain = cookie.getDomain();
        if (domain != null && domain.length() > 0) {
            buf.append(";Domain=");
            buf.append(domain.toLowerCase());// lowercase for IE
        }
        long maxAge = cookie.getMaxAge();
        if (maxAge >= 0) {
            if (version == 0) {
                buf.append(";Expires=");
                if (maxAge == 0)
                    buf.append(__01Jan1970);
                else
                    formatDate(buf, System.currentTimeMillis() + 1000L * maxAge, true);
            } else {
                buf.append(";Max-Age=");
                buf.append(cookie.getMaxAge());
            }
        } else if (version > 0) {
            buf.append(";Discard");
        }
        if (cookie.getSecure()) {
            buf.append(";Secure");
        }
        if (cookie instanceof HttpOnlyCookie)
            buf.append(";HttpOnly");

        name_value_params = buf.toString();
    }
    put(__Expires, __01Jan1970);
    add(__SetCookie, name_value_params);
}

From source file:com.googlesource.gerrit.plugins.github.oauth.OAuthWebFilter.java

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

    HttpServletRequest httpRequest = (HttpServletRequest) request;
    HttpServletResponse httpResponse = (HttpServletResponse) response;
    log.debug("OAuthWebFilter(" + httpRequest.getRequestURL() + ") code=" + request.getParameter("code"));

    Cookie gerritCookie = getGerritCookie(httpRequest);
    try {/*  w ww  . j av  a 2  s  . c o  m*/
        GitHubLogin ghLogin = loginProvider.get(httpRequest);

        if (OAuthProtocol.isOAuthLogout(httpRequest)) {
            logout(request, response, chain, httpRequest);
        } else if (OAuthProtocol.isOAuthRequest(httpRequest) && !ghLogin.isLoggedIn()) {
            login(request, httpRequest, httpResponse, ghLogin);
        } else {
            if (ghLogin != null && ghLogin.isLoggedIn()) {
                httpRequest = new AuthenticatedHttpRequest(httpRequest, config.httpHeader,
                        ghLogin.getMyself().getLogin(), config.oauthHttpHeader,
                        GITHUB_EXT_ID + ghLogin.getToken().accessToken);
            }

            if (OAuthProtocol.isOAuthFinalForOthers(httpRequest)) {
                httpResponse.sendRedirect(OAuthProtocol.getTargetOAuthFinal(httpRequest));
            } else {
                chain.doFilter(httpRequest, response);
            }
        }
    } finally {
        HttpSession httpSession = httpRequest.getSession();
        if (gerritCookie != null && httpSession != null) {
            String gerritCookieValue = gerritCookie.getValue();
            String gerritSessionValue = (String) httpSession.getAttribute("GerritAccount");

            if (gerritSessionValue == null) {
                httpSession.setAttribute("GerritAccount", gerritCookieValue);
            } else if (!gerritSessionValue.equals(gerritCookieValue)) {
                httpSession.invalidate();
            }
        }
    }
}

From source file:com.adito.security.DefaultLogonController.java

public int hasClientLoggedOn(HttpServletRequest request, HttpServletResponse response)
        throws SecurityErrorException {
    // Get the logon cookie
    String logonCookie = null;/*www  .  j  a  va2s .com*/
    if (request.getCookies() != null) {
        for (int i = 0; i < request.getCookies().length; i++) {
            Cookie cookie = request.getCookies()[i];
            if (cookie.getName().equals(Constants.LOGON_TICKET)
                    || cookie.getName().equals(Constants.DOMAIN_LOGON_TICKET)) {
                logonCookie = cookie.getValue();
            }
        }
    }
    // If there is a logon ticket in the requests attributes then reassign
    // as we've just been issued a new ticket.
    if (request.getAttribute(Constants.LOGON_TICKET) != null)
        logonCookie = (String) request.getAttribute(Constants.LOGON_TICKET);
    // First check the users session for a logonticket
    String sessionLogonTicket = (String) request.getSession().getAttribute(Constants.LOGON_TICKET);
    if (sessionLogonTicket != null) {
        // Make sure we are still receiving the logon ticket
        /**
         * LDP - Users are having too many issues with this change. If we
         * still have a ticket in the session then the HTTP session must
         * still be alive and the the cookie has simply expired before the
         * HTTP session (or the browser has elected not to send it). We
         * should allow this to continue and refresh the cookie here.
         */
        /*
         * if(logonCookie == null &&
         * request.getAttribute(Constants.LOGON_TICKET) == null) {
         * 
         * 
         * log.warn("Lost logon ticket. It is likely that logon cookie has
         * expired. "); return INVALID_TICKET; } else
         */
        if (logonCookie == null) {

            SessionInfo session = getSessionInfo(sessionLogonTicket);
            if (session == null)
                return NOT_LOGGED_ON;
            addCookies(new ServletRequestAdapter(request), new ServletResponseAdapter(response),
                    sessionLogonTicket, session);
        }
        // Still check that the cookie is what we expect it to be
        if (logonCookie != null && !sessionLogonTicket.equals(logonCookie)) {
            log.warn("Expected a different logon ticket.");
            return NOT_LOGGED_ON;
        }

        if (checkRemoteAddress(sessionLogonTicket, request.getRemoteAddr())) {
            return LOGGED_ON;
        }
    } else {
        if (logonCookie != null && logons.containsKey(logonCookie)) {
            if (checkRemoteAddress(logonCookie, request.getRemoteAddr())) {
                refreshLogonTicket(request, response, logonCookie);
                return LOGGED_ON;
            }
        }
    }
    return NOT_LOGGED_ON;
}

From source file:com.twelve.capital.external.feed.util.HttpImpl.java

protected Cookie toServletCookie(org.apache.commons.httpclient.Cookie commonsCookie) {

    Cookie cookie = new Cookie(commonsCookie.getName(), commonsCookie.getValue());

    if (!PropsValues.SESSION_COOKIE_USE_FULL_HOSTNAME) {
        String domain = commonsCookie.getDomain();

        if (Validator.isNotNull(domain)) {
            cookie.setDomain(domain);//from   w  w  w .jav  a  2  s. c  o m
        }
    }

    Date expiryDate = commonsCookie.getExpiryDate();

    if (expiryDate != null) {
        int maxAge = (int) (expiryDate.getTime() - System.currentTimeMillis());

        maxAge = maxAge / 1000;

        if (maxAge > -1) {
            cookie.setMaxAge(maxAge);
        }
    }

    String path = commonsCookie.getPath();

    if (Validator.isNotNull(path)) {
        cookie.setPath(path);
    }

    cookie.setSecure(commonsCookie.getSecure());
    cookie.setVersion(commonsCookie.getVersion());

    return cookie;
}