Save RequestsCookieJar to disk in Mozilla's cookies.txt file format.

    This prevents us from repeated authentications on the
    accounts.coursera.org and class.coursera.org/class_name sites.
556106
def write_cookies_to_cache(cj, username):
    
    mkdir_p(PATH_COOKIES, 0o700)
    path = get_cookies_cache_path(username)
    cached_cj = cookielib.MozillaCookieJar()
    for cookie in cj:
        cached_cj.set_cookie(cookie)
    cached_cj.save(path)
736407
def save(self):
        
        if self.path.is_collection:
            self.session.post_json(self.href,
                                   {self.type: dict(self.data)},
                                   cls=ResourceEncoder)
        else:
            self.session.put_json(self.href,
                                  {self.type: dict(self.data)},
                                  cls=ResourceEncoder)
        return self.fetch(exclude_children=True, exclude_back_refs=True)
556351
public void save(HttpServletRequest req, HttpServletResponse res) {
		AuthenticationResult authResult = new AuthenticationResult(AuthResult.SUCCESS, (String) null);
		save(req, res, authResult);
		List<Cookie> cookieList = authResult.getCookies();
		if (cookieList != null && cookieList.size() > 0) {
			CookieHelper.addCookiesToResponse(cookieList, res);
		}
	}
1359936
def client_cookie_jar(self):
		
		cookie_jar = WHTTPCookieJar()
		cookie_header = self.get_headers('Cookie')
		for cookie_string in (cookie_header if cookie_header is not None else tuple()):
			for single_cookie in WHTTPCookieJar.import_header_text(cookie_string):
				cookie_jar.add_cookie(single_cookie)

		return cookie_jar.ro()
541494
def save(self, set_cookie, **params):
        """"""
        if set(self.store.items()) ^ set(self.items()):
            value = dict(self.items())
            value = json.dumps(value)
            value = self.encrypt(value)
            if not isinstance(value, str):
                value = value.encode(self.encoding)
            set_cookie(self.key, value, **self.params)
            return True
        return False
178485
def make_cookie_values(cj, class_name):
    
    path = "/" + class_name

    cookies = [c.name + '=' + c.value
               for c in cj
               if c.domain == "class.coursera.org"
               and c.path == path]

    return '; '.join(cookies)
842406
def extract_cookiejar(self):
        

        # Example of line:
        # www.google.com\tFALSE\t/accounts/\tFALSE\t0'
        # \tGoogleAccountsLocale_session\ten
        # Fields:
        # * domain
        # * whether or not all machines under that domain can
        # read the cookie's information.
        # * path
        # * Secure Flag: whether or not a secure connection (HTTPS)
        # is required to read the cookie.
        # * exp. timestamp
        # * name
        # * value
        cookiejar = CookieJar()
        for line in self.curl.getinfo(pycurl.INFO_COOKIELIST):
            values = line.split('\t')
            domain = values[0].lower()
            if domain.startswith('#httponly_'):
                domain = domain.replace('#httponly_', '')
                httponly = True
            else:
                httponly = False
            # old
            # cookies[values[-2]] = values[-1]
            # new
            cookie = create_cookie(
                name=values[5],
                value=values[6],
                domain=domain,
                path=values[2],
                secure=values[3] == "TRUE",
                expires=int(values[4]) if values[4] else None,
                httponly=httponly,
            )
            cookiejar.set_cookie(cookie)
        return cookiejar
715979
def StoreCSRFCookie(user, response):
  """"""

  csrf_token = GenerateCSRFToken(user, None)
  response.set_cookie(
      "csrftoken", csrf_token, max_age=CSRF_TOKEN_DURATION.seconds)
1193282
def close(self):
        ''''''
        if self._save_filename:
            self._cookie_jar.save(
                self._save_filename,
                ignore_discard=self._keep_session_cookies
            )
843955
def find_cookies_for_class(cookies_file, class_name):
    

    path = "/" + class_name

    def cookies_filter(c):
        return c.domain == ".coursera.org" \
            or (c.domain == "class.coursera.org" and c.path == path)

    cj = get_cookie_jar(cookies_file)

    new_cj = requests.cookies.RequestsCookieJar()
    for c in filter(cookies_filter, cj):
        new_cj.set_cookie(c)

    return new_cj
158917
def load_cookies_file(cookies_file):
    

    logging.debug('Loading cookie file %s into memory.', cookies_file)

    cookies = StringIO()
    cookies.write('# Netscape HTTP Cookie File')
    cookies.write(open(cookies_file, 'rU').read())
    cookies.flush()
    cookies.seek(0)
    return cookies
225047
function (path, onDone) {

		var options = {cookie: cookie};
		var contentType = contentTypesByExtension[pathLib.extname(path)];
		if (contentType) 
			options['content_type'] = contentType;
				
		LOG.sys('try to serve: ' + path, 'handlers.REST_web');

		/*
		*/
		
		// NOTE: file can either not exist, or path can be a directory, need to consider both cases
		l_readFile(path, function (data) {				
			if (data) {
				LOG.sys('finished reading file: ' + path, 'handlers.REST_web');
				onReturnFile(data, options);
				UTIL.safeCall(onDone, true);
			}
			else
				UTIL.safeCall(onDone, false);
		});		
	}
1294416
def cookietostr(self):
        ""
        self.cookies = dict((k, (v.decode(self.encoding) if not isinstance(v, str) else v)) for k,v in self.cookies.items())
        return self.cookies
1098941
public static void storeSessionDataInCookie(String key, String value, ServletResponse response)
	{
		Cookie cookie = new Cookie(key, value);
		cookie.setPath("/");
		cookie.setMaxAge(-1);//expire when browser closes
		((HttpServletResponse) response).addCookie(cookie);
	}
376113
private void saveResponseCookies() throws IOException {
    CookieHandler cookieHandler = CookieHandler.getDefault();
    if (cookieHandler != null) {
      try {
        URI uri = getURL().toURI();
        cookieHandler.put(uri, getHeaderFieldsDoNotForceResponse());
      } catch (URISyntaxException e) {
        throw new IOException(e);
      }
    }
  }
1241229
def get_cookies(self):
		'''
		
		'''
		ret = self.Network_getAllCookies()

		assert 'result' in ret, "No return value in function response!"
		assert 'cookies' in ret['result'], "No 'cookies' key in function response"

		cookies = []
		for raw_cookie in ret['result']['cookies']:

			# Chromium seems to support the following key values for the cookie dict:
			# 	"name"
			# 	"value"
			# 	"domain"
			# 	"path"
			# 	"expires"
			# 	"httpOnly"
			# 	"session"
			# 	"secure"
			#
			#  This seems supported by the fact that the underlying chromium cookie implementation has
			#  the following members:
			#        std::string name_;
			#        std::string value_;
			#        std::string domain_;
			#        std::string path_;
			#        base::Time creation_date_;
			#        base::Time expiry_date_;
			#        base::Time last_access_date_;
			#        bool secure_;
			#        bool httponly_;
			#        CookieSameSite same_site_;
			#        CookiePriority priority_;
			#
			# See chromium/net/cookies/canonical_cookie.h for more.
			#
			# I suspect the python cookie implementation is derived exactly from the standard, while the
			# chromium implementation is more of a practically derived structure.

			# Network.setCookie

			baked_cookie = http.cookiejar.Cookie(
					# We assume V0 cookies, principally because I don't think I've /ever/ actually encountered a V1 cookie.
					# Chromium doesn't seem to specify it.
					version            = 0,

					name               = raw_cookie['name'],
					value              = raw_cookie['value'],
					port               = None,
					port_specified     = False,
					domain             = raw_cookie['domain'],
					domain_specified   = True,
					domain_initial_dot = False,
					path               = raw_cookie['path'],
					path_specified     = False,
					secure             = raw_cookie['secure'],
					expires            = raw_cookie['expires'],
					discard            = raw_cookie['session'],
					comment            = None,
					comment_url        = None,
					rest               = {"httponly":"%s" % raw_cookie['httpOnly']},
					rfc2109            = False
				)
			cookies.append(baked_cookie)

		return cookies
712446
def filter_cookies(self, request_url: URL=URL()) -> 'BaseCookie[str]':
        """"""
        self._do_expiration()
        request_url = URL(request_url)
        filtered = SimpleCookie()
        hostname = request_url.raw_host or ""
        is_not_secure = request_url.scheme not in ("https", "wss")

        for cookie in self:
            name = cookie.key
            domain = cookie["domain"]

            # Send shared cookies
            if not domain:
                filtered[name] = cookie.value
                continue

            if not self._unsafe and is_ip_address(hostname):
                continue

            if (domain, name) in self._host_only_cookies:
                if domain != hostname:
                    continue
            elif not self._is_domain_match(domain, hostname):
                continue

            if not self._is_path_match(request_url.path, cookie["path"]):
                continue

            if is_not_secure and cookie["secure"]:
                continue

            # It's critical we use the Morsel so the coded_value
            # (based on cookie version) is preserved
            mrsl_val = cast('Morsel[str]', cookie.get(cookie.key, Morsel()))
            mrsl_val.set(cookie.key, cookie.value, cookie.coded_value)
            filtered[name] = mrsl_val

        return filtered