Parses a single cookie

@param cookies the array of cookies read
@param rawCookie the input for the cookie
482368
private void fillCookie(ArrayList<WebCookie> cookies, CharSegment rawCookie)
  {
    char []buf = rawCookie.buffer();
    int j = rawCookie.offset();
    int end = j + rawCookie.length();
    int version = 0;
    WebCookie cookie = null;

    while (j < end) {
      char ch = 0;

      CharBuffer cbName = _cbName;
      CharBuffer cbValue = _cbValue;

      cbName.clear();
      cbValue.clear();

      for (;
           j < end && ((ch = buf[j]) == ' ' || ch == ';' || ch ==',');
           j++) {
      }

      if (end <= j)
        break;

      boolean isSpecial = false;
      if (buf[j] == '$') {
        isSpecial = true;
        j++;
      }

      for (; j < end; j++) {
        ch = buf[j];
        if (ch < 128 && TOKEN[ch])
          cbName.append(ch);
        else
          break;
      }

      for (; j < end && (ch = buf[j]) == ' '; j++) {
      }

      if (end <= j)
        break;
      else if (ch == ';' || ch == ',') {
        try {
          cookie = new WebCookie(cbName.toString(), "");
          cookie.setVersion(version);
          _cookies.add(cookie);
          // some clients can send bogus cookies
        } catch (Exception e) {
          log.log(Level.FINE, e.toString(), e);
        }
        continue;
      }
      else if (ch != '=') {
        for (; j < end && (ch = buf[j]) != ';'; j++) {
        }
        continue;
      }

      j++;

      for (; j < end && (ch = buf[j]) == ' '; j++) {
      }

      if (ch == '"') {
        for (j++; j < end; j++) {
          ch = buf[j];
          if (ch == '"')
            break;
          cbValue.append(ch);
        }
        j++;
      }
      else {
        int head = j;
        int tail = j;
        
        for (; j < end; j++) {
          ch = buf[j];
          if (ch < 128 && VALUE[ch]) {
            cbValue.append(ch);
            tail = j + 1;
          }
          else if (ch == ' ') {
            cbValue.append(ch);
            // server/01ed
          }
          else {
            break;
          }
        }
        
        cbValue.length(tail - head);
      }

      if (! isSpecial) {
        if (cbName.length() == 0)
          log.warning("bad cookie: " + rawCookie);
        else {
          cookie = new WebCookie(toName(cbName), cbValue.toString());
          cookie.setVersion(version);
          _cookies.add(cookie);
        }
      }
      else if (cookie == null) {
        if (cbName.matchesIgnoreCase("Version"))
          version = cbValue.charAt(0) - '0';
      }
      else if (cbName.matchesIgnoreCase("Version"))
        cookie.setVersion(cbValue.charAt(0) - '0');
      else if (cbName.matchesIgnoreCase("Domain"))
        cookie.setDomain(cbValue.toString());
      else if (cbName.matchesIgnoreCase("Path"))
        cookie.setPath(cbValue.toString());
    }
  }
367798
def parse_headers(self, use_cookies, raw):
        
        if not raw:
            packet = helper.to_str(helper.read_file(self.fpth))
        else:
            packet = raw
        dat = {}

        pks = [x for x in packet.split('\n') if x.replace(' ', '')]
        url = pks[0].split(' ')[1]

        for i, cnt in enumerate(pks[1:]):
            arr = cnt.split(':')
            if len(arr) < 2:
                continue
            arr = [x.replace(' ', '') for x in arr]
            _k, v = arr[0], ':'.join(arr[1:])
            dat[_k] = v

        if use_cookies:
            try:
                self.fmt_cookies(dat.pop('Cookie'))
            except:
                pass
        self.headers = dat
        self.url = 'https://{}{}'.format(self.headers.get('Host'), url)
        return url, dat
571977
public HttpResponse addCookie(Collection<HttpCookie> cookies) {
        this.cookies = Utility.append(this.cookies, cookies);
        return this;
    }
923703
private function parseCookie($cookie, $host = null, $path = null, $decode = false) {
        // Explode the cookie string using a series of semicolons
        $pieces = array_filter(array_map('trim', explode(';', $cookie)));

        // The name of the cookie (first kvp) must include an equal sign.
        if (empty($pieces) || !strpos($pieces[0], '=')) {
            return false;
        }

        // Create the default return array
        $data = array_merge(array_fill_keys(array_keys(self::$cookieParts), null), array(
            'cookies'   => array(),
            'data'      => array(),
            'path'      => $path ?: '/',
            'http_only' => false,
            'discard'   => false,
            'domain'    => $host
        ));
        $foundNonCookies = 0;

        // Add the cookie pieces into the parsed data array
        foreach ($pieces as $part) {

            $cookieParts = explode('=', $part, 2);
            $key = trim($cookieParts[0]);

            if (count($cookieParts) == 1) {
                // Can be a single value (e.g. secure, httpOnly)
                $value = true;
            } else {
                // Be sure to strip wrapping quotes
                $value = trim($cookieParts[1], " \n\r\t\0\x0B\"");
                if ($decode) {
                    $value = urldecode($value);
                }
            }

            // Only check for non-cookies when cookies have been found
            if (!empty($data['cookies'])) {
                foreach (self::$cookieParts as $mapValue => $search) {
                    if (!strcasecmp($search, $key)) {
                        $data[$mapValue] = $mapValue == 'port' ? array_map('trim', explode(',', $value)) : $value;
                        $foundNonCookies++;
                        continue 2;
                    }
                }
            }

            // If cookies have not yet been retrieved, or this value was not found in the pieces array, treat it as a
            // cookie. IF non-cookies have been parsed, then this isn't a cookie, it's cookie data. Cookies then data.
            $data[$foundNonCookies ? 'data' : 'cookies'][$key] = $value;
        }

        // Calculate the expires date
        if (!$data['expires'] && $data['max_age']) {
            $data['expires'] = time() + (int) $data['max_age'];
        }

        return $data;
    }
1244731
@SafeVarargs
    public final RequestBuilder cookies(Map.Entry<String, ?>... cookies) {
        cookies(Lists.of(cookies));
        return this;
    }
870872
def parse_one_response(line, ignore_bad_cookies=False,
                       ignore_bad_attributes=True):
    
    cookie_dict = {}
    # Basic validation, extract name/value/attrs-chunk
    match = Definitions.SET_COOKIE_HEADER_RE.match(line)
    if not match:
        if not ignore_bad_cookies:
            raise InvalidCookieError(data=line)
        _report_invalid_cookie(line)
        return None
    cookie_dict.update({
        'name': match.group('name'),
        'value': match.group('value')})
    # Extract individual attrs from the attrs chunk
    for match in Definitions.ATTR_RE.finditer(match.group('attrs')):
        captured = dict((k, v) for (k, v) in match.groupdict().items() if v)
        unrecognized = captured.get('unrecognized', None)
        if unrecognized:
            if not ignore_bad_attributes:
                raise InvalidCookieAttributeError(None, unrecognized,
                                                  "unrecognized")
            _report_unknown_attribute(unrecognized)
            continue
        # for unary flags
        for key in ('secure', 'httponly'):
            if captured.get(key):
                captured[key] = True
        # ignore subcomponents of expires - they're still there to avoid doing
        # two passes
        timekeys = ('weekday', 'month', 'day', 'hour', 'minute', 'second',
                    'year')
        if 'year' in captured:
            for key in timekeys:
                del captured[key]
        elif 'year2' in captured:
            for key in timekeys:
                del captured[key + "2"]
        cookie_dict.update(captured)
    return cookie_dict
634410
public final static Map<String, Cookie> readCookieMap(HttpServletRequest httpServletRequest) {
		Map<String, Cookie> cookieMap = new HashMap<String, Cookie>();
		Cookie[] cookies = httpServletRequest.getCookies();
		if (null == cookies) {
			return null;
		}
		for (Cookie cookie : cookies) {
			cookieMap.put(cookie.getName().toLowerCase(), cookie);
		}
		return cookieMap;
	}
957793
public List<String> encode(Collection<? extends Cookie> cookies) {
        if (checkNotNull(cookies, "cookies").isEmpty()) {
            return Collections.emptyList();
        }

        List<String> encoded = new ArrayList<String>(cookies.size());
        Map<String, Integer> nameToIndex = strict && cookies.size() > 1 ? new HashMap<String, Integer>() : null;
        int i = 0;
        boolean hasDupdName = false;
        for (Cookie c : cookies) {
            encoded.add(encode(c));
            if (nameToIndex != null) {
                hasDupdName |= nameToIndex.put(c.name(), i++) != null;
            }
        }
        return hasDupdName ? dedup(encoded, nameToIndex) : encoded;
    }
640699
protected function setCookiesFromRawHeader($rawFieldValue)
    {
        $cookiePairs = explode(';', $rawFieldValue);
        foreach ($cookiePairs as $cookiePair) {
            if (strpos($cookiePair, '=') === false) {
                continue;
            }
            list($name, $value) = explode('=', $cookiePair, 2);
            $trimmedName = trim($name);

            if ($trimmedName !== '' && preg_match(Cookie::PATTERN_TOKEN, $trimmedName) === 1) {
                $this->setCookie(new Cookie($trimmedName, urldecode(trim($value, "\t ;\""))));
            }
        }
    }
1284969
public static Cookie convertNettyCookieToWisdomCookie(DefaultCookie cookie) {
        Preconditions.checkNotNull(cookie);
        String value = cookie.value();
//        // Netty append some data at the end f the cookie:
//        // -createdBy=wisdom&at=3+nov.+2013+11%3A52%3A15&___TS=1383475935779, path=/, maxAge=3600s, secure, HTTPOnly
//        // We have to remove them
//        // TODO Do we really need this ? It was probably related to the cookie encoding issue.
//        if (value.contains(PATH)) {
//            value = value.substring(0, value.indexOf(PATH));
//        }

        Cookie.Builder builder
                = Cookie.builder(cookie.name(), value);

        builder.setMaxAge(cookie.maxAge());

        if (cookie.domain() != null) {
            builder.setDomain(cookie.domain());
        }

        builder.setSecure(cookie.isSecure());

        if (cookie.path() != null) {
            builder.setPath(cookie.path());
        }

        builder.setHttpOnly(cookie.isHttpOnly());

        return builder.build();
    }
97932
public Cookie[] getCookies()
    {
        if (_cookies != null && _cookiesExtracted) return _cookies;

        try
        {
            // Handle no cookies
            if (!_header.containsKey(HttpFields.__Cookie))
            {
                _cookies = __noCookies;
                _cookiesExtracted = true;
                _lastCookies = null;
                return _cookies;
            }

            // Check if cookie headers match last cookies
            if (_lastCookies != null)
            {
                int last = 0;
                Enumeration enm = _header.getValues(HttpFields.__Cookie);
                while (enm.hasMoreElements())
                {
                    String c = (String) enm.nextElement();
                    if (last >= _lastCookies.length || !c.equals(_lastCookies[last]))
                    {
                        _lastCookies = null;
                        break;
                    }
                    last++;
                }
                if (_lastCookies != null)
                {
                    _cookiesExtracted = true;
                    return _cookies;
                }
            }

            // Get ready to parse cookies (Expensive!!!)
            Object cookies = null;
            Object lastCookies = null;

            int version = 0;
            Cookie cookie = null;

            // For each cookie header
            Enumeration enm = _header.getValues(HttpFields.__Cookie);
            while (enm.hasMoreElements())
            {
                // Save a copy of the unparsed header as cache.
                String hdr = enm.nextElement().toString();
                lastCookies = LazyList.add(lastCookies, hdr);

                // Parse the header
                QuotedStringTokenizer tok = new QuotedStringTokenizer(hdr, ",;", false, false);
                tok.setSingle(false);
                while (tok.hasMoreElements())
                {
                    String c = (String) tok.nextElement();
                    if (c == null) continue;
                    c = c.trim();

                    try
                    {
                        String n;
                        String v;
                        int e = c.indexOf('=');
                        if (e > 0)
                        {
                            n = c.substring(0, e);
                            v = c.substring(e + 1);
                        }
                        else
                        {
                            n = c;
                            v = "";
                        }

                        // Handle quoted values
                        if (version > 0) v = StringUtil.unquote(v);

                        // Ignore $ names
                        if (n.startsWith("$"))
                        {
                            if ("$version".equalsIgnoreCase(n))
                                version = Integer.parseInt(QuotedStringTokenizer.unquoteDouble(v));
                            else if ("$path".equalsIgnoreCase(n) && cookie != null)
                                cookie.setPath(v);
                            else if ("$domain".equalsIgnoreCase(n) && cookie != null)
                                    cookie.setDomain(v);
                            continue;
                        }

                        v = URI.decodePath(v);
                        cookie = new Cookie(n, v);
                        if (version > 0) cookie.setVersion(version);
                        cookies = LazyList.add(cookies, cookie);
                    }
                    catch (Exception ex)
                    {
                        LogSupport.ignore(log, ex);
                    }
                }
            }

            int l = LazyList.size(cookies);
            if (_cookies == null || _cookies.length != l) _cookies = new Cookie[l];
            for (int i = 0; i < l; i++)
                _cookies[i] = (Cookie) LazyList.get(cookies, i);
            _cookiesExtracted = true;

            l = LazyList.size(lastCookies);
            _lastCookies = new String[l];
            for (int i = 0; i < l; i++)
                _lastCookies[i] = (String) LazyList.get(lastCookies, i);

        }
        catch (Exception e)
        {
            log.warn(LogSupport.EXCEPTION, e);
        }

        return _cookies;
    }
694797
private String toCookieStr(Cookie[] cookies) {
    String cookieStr = "";

    for (Cookie c : cookies) {
     cookieStr += c.getName() + "=" + c.getValue() + " ;\n";
    }
    return cookieStr;
  }
1326664
protected function _parseCookies($headers) {
		foreach ((array) $headers as $header) {
			$parts = array_map('trim', array_filter(explode('; ', $header)));
			$cookie = array_shift($parts);
			list($name, $value) = array_map('urldecode', explode('=', $cookie, 2)) + ['',''];

			$options = [];
			foreach ($parts as $part) {
				$part = array_map('urldecode', explode('=', $part, 2)) + ['',''];
				$options[strtolower($part[0])] = $part[1] ?: true;
			}
			if (isset($options['expires'])) {
				$options['expires'] = strtotime($options['expires']);
			}
			$this->cookies($name, compact('value') + $options);
		}
	}
1195145
@Override
    public Cookie[] getCookies() {
        List<HttpCookie> cookies = this.request.getCookies();
        if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
            Tr.debug(tc, "getCookies: " + cookies.size());
        }
        if (cookies.isEmpty()) {
            return null;
        }
        Cookie[] output = new Cookie[cookies.size()];
        int i = 0;
        for (HttpCookie cookie : cookies) {
            output[i++] = new Cookie(cookie.getName(), cookie.getValue());
        }
        return output;
    }
229046
private void parseIDFromCookies(RequestMessage request) {
        if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
            Tr.debug(tc, "Looking for ID in cookies");
        }
        Enumeration<String> list = request.getHeaders("Cookie");
        while (list.hasMoreElements()) {
            String item = list.nextElement();
            int index = item.indexOf(getSessionConfig().getIDName());
            if (-1 != index) {
                index = item.indexOf('=', index);
                if (-1 != index) {
                    index++;
                    // TODO this is assuming that the full value is valid and
                    // grabbing just the 4 digit id...
                    if (item.length() >= (index + 4)) {
                        this.id = item.substring(index, index + 4);
                        this.fromCookie = true;
                        break;
                    }
                }
            }
        }
    }
437058
public static function setCookieHeaders($cookies)
    {
        if (!empty($cookies) && is_array($cookies) && false === headers_sent() && !self::isTest()) {
            foreach ($cookies as $cookie) {
                setcookie($cookie["name"],
                    $cookie["value"],
                    (array_key_exists('expire', $cookie)) ? $cookie["expire"] : NULL,
                    (array_key_exists('path', $cookie)) ? $cookie["path"] : "/",
                    (array_key_exists('domain', $cookie)) ? $cookie["domain"] : Request::getInstance()->getRootUrl(FALSE),
                    (array_key_exists('secure', $cookie)) ? $cookie["secure"] : FALSE,
                    (array_key_exists('http', $cookie)) ? $cookie["http"] : true
                );
            }
        }
    }
539418
public static Cookie[] parseCookieHeader( String header ) {

        if ((header == null) || (header.length() < 1)) {
            return (new Cookie[0]);
        }

        ArrayList<Cookie> cookies = new ArrayList<Cookie>();
        while (header.length() > 0) {
            int semicolon = header.indexOf(';');
            if (semicolon < 0) {
                semicolon = header.length();
            }
            if (semicolon == 0) {
                break;
            }
            String token = header.substring(0, semicolon);
            if (semicolon < header.length()) {
                header = header.substring(semicolon + 1);
            } else {
                header = "";
            }
            try {
                int equals = token.indexOf('=');
                if (equals > 0) {
                    String name = token.substring(0, equals).trim();
                    String value = token.substring(equals + 1).trim();
                    cookies.add(new Cookie(name, value));
                }
            } catch (Throwable e) {
                // do nothing ?!
            }
        }

        return cookies.toArray(new Cookie[cookies.size()]);
    }