Gets the cookie for the Authorized connection to the Hub server. Returns the response code from the connection.
549235
@Override
    public void authenticateWithBlackduck() throws IntegrationException {
        final URL securityUrl;
        try {
            securityUrl = new URL(getBaseUrl(), "j_spring_security_check");
        } catch (final MalformedURLException e) {
            throw new IntegrationException("Error constructing the login URL: " + e.getMessage(), e);
        }

        if (StringUtils.isNotBlank(hubUsername) && StringUtils.isNotBlank(hubPassword)) {
            final List<NameValuePair> bodyValues = new ArrayList<>();
            bodyValues.add(new BasicNameValuePair("j_username", hubUsername));
            bodyValues.add(new BasicNameValuePair("j_password", hubPassword));
            final UrlEncodedFormEntity entity = new UrlEncodedFormEntity(bodyValues, Charsets.UTF_8);

            final RequestBuilder requestBuilder = createRequestBuilder(HttpMethod.POST, null);
            requestBuilder.setCharset(Charsets.UTF_8);
            requestBuilder.setUri(securityUrl.toString());
            requestBuilder.setEntity(entity);
            final HttpUriRequest request = requestBuilder.build();
            logRequestHeaders(request);
            try (final CloseableHttpResponse closeableHttpResponse = getClient().execute(request)) {
                logResponseHeaders(closeableHttpResponse);
                final Response response = new Response(closeableHttpResponse);
                final int statusCode = closeableHttpResponse.getStatusLine().getStatusCode();
                final String statusMessage = closeableHttpResponse.getStatusLine().getReasonPhrase();
                if (statusCode < RestConstants.OK_200 || statusCode >= RestConstants.MULT_CHOICE_300) {
                    final String httpResponseContent = response.getContentString();
                    throw new IntegrationRestException(statusCode, statusMessage, httpResponseContent, String.format("Connection Error: %s %s", statusCode, statusMessage));
                } else {
                    // get the CSRF token
                    final Header csrfToken = closeableHttpResponse.getFirstHeader(RestConstants.X_CSRF_TOKEN);
                    if (csrfToken != null) {
                        addCommonRequestHeader(RestConstants.X_CSRF_TOKEN, csrfToken.getValue());
                    } else {
                        logger.error("No CSRF token found when authenticating");
                    }
                }
            } catch (final IOException e) {
                throw new IntegrationException(e.getMessage(), e);
            }
        }
    }
56475
def get_session(username, password, locale=DEFAULT_LOCALE,
                cookie_path=COOKIE_PATH):
    """"""
    class UPSAuth(AuthBase):  # pylint: disable=too-few-public-methods
        """UPS authorization storage."""

        def __init__(self, username, password, locale, cookie_path):
            """Init."""
            self.username = username
            self.password = password
            self.locale = locale
            self.cookie_path = cookie_path

        def __call__(self, r):
            """Call is no-op."""
            return r

    session = requests.session()
    session.auth = UPSAuth(username, password, locale, cookie_path)
    if os.path.exists(cookie_path):
        session.cookies = _load_cookies(cookie_path)
    else:
        _login(session)
    return session
529319
String getCookieString(Cookie cookie) {
        StringBuilder builder = new StringBuilder();

        builder.append(cookie.getName());
        builder.append("=");
        builder.append(cookie.getValue());

        if (cookie.getVersion() > 0) {
            builder.append(";" + VERSION + "=").append(cookie.getVersion());
        }

        if (StringUtils.hasText(cookie.getPath())) {
            builder.append(";" + PATH + "=").append(cookie.getPath());
        }

        if (StringUtils.hasText(cookie.getDomain())) {
            builder.append(";" + DOMAIN + "=").append(cookie.getDomain());
        }

        if (cookie.getMaxAge() > 0) {
            builder.append(";" + MAX_AGE + "=").append(cookie.getMaxAge());
        }

        if (StringUtils.hasText(cookie.getComment())) {
            builder.append(";" + COMMENT + "=").append(cookie.getComment());
        }

        if (cookie.getSecure()) {
            builder.append(";" + SECURE);
        }

        if (cookie.isHttpOnly()) {
            builder.append(";" + HTTP_ONLY);
        }

        return builder.toString();
    }
1286438
function getSession (ctx) {
    let signedCookie = ctx.cookies.get(sessionKey, {signed: cookie.signed}) || ''
    signedCookie = signedCookie.split('.')

    return ctx.thunk()(function () {
      if (!storeAvailable) throw new Error('session store is not available')
      if (signedCookie[0]) return store.get(signedCookie[0])
    })(function (err, session) {
      if (err) throw err
      let sessionId
      let originalHash

      if (session) {
        sessionId = signedCookie[0]
        originalHash = signedCookie[1]
        if (hashSession(session, sessionId) !== originalHash) session = null
      }

      if (!session) {
        session = genSession()
        sessionId = genSid(sidSize)
        originalHash = hashSession(session, sessionId)
      }

      return {
        session: session,
        sessionId: sessionId,
        originalHash: originalHash,
        isNew: originalHash !== signedCookie[1]
      }
    })
  }
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
156219
public final HttpServer cookieCodec(ServerCookieEncoder encoder, ServerCookieDecoder decoder) {
		return tcpConfiguration(tcp -> tcp.bootstrap(
				b -> HttpServerConfiguration.cookieCodec(b, encoder, decoder)));
	}
830665
def cookies(self):
        
        cookies = SimpleCookie()
        cookie = self.environ.get('HTTP_COOKIE')
        if cookie:
            cookies.load(cookie)
        return cookies
774351
def request(self, method, url, **kwargs):
        
        # The CookieJar API prevents callers from getting an individual Cookie
        # object by name.
        # We are forced to use the only exposed method of discarding expired
        # cookies from the CookieJar. Internally this involves iterating over
        # the entire CookieJar and calling `.is_expired()` on each Cookie
        # object.
        self.cookies.clear_expired_cookies()

        if self._auto_renew and 'IAMSession' not in self.cookies.keys():
            self.login()

        resp = super(IAMSession, self).request(method, url, **kwargs)

        if not self._auto_renew:
            return resp

        if resp.status_code == 401:
            self.login()
            resp = super(IAMSession, self).request(method, url, **kwargs)

        return resp
776906
def _get_session(self, request):
        
        _session = requests.session()  # empty session
        
        response = _session.post(**request)
        logger.info('Using SMC API version: %s', self.api_version)
        
        if response.status_code != 200:
            raise SMCConnectionError(
                'Login failed, HTTP status code: %s and reason: %s' % (
                    response.status_code, response.reason))
        return _session
655791
def _get_response(self):
        
        try:
            self._open_connection()
            if self.connection is None:
                # The connection wasn't opened, which means we're deferring a reconnection attempt.
                # Raise a socket.error, so we'll return the same server_disconnected message as we
                # do below.
                raise socket.error('Delaying reconnection attempt')

            header = self._read_socket(self.HEADER_SIZE)
            (magic, opcode, keylen, extlen, datatype, status, bodylen, opaque,
             cas) = struct.unpack(self.HEADER_STRUCT, header)

            assert magic == self.MAGIC['response']

            extra_content = None
            if bodylen:
                extra_content = self._read_socket(bodylen)

            return (magic, opcode, keylen, extlen, datatype, status, bodylen,
                    opaque, cas, extra_content)
        except socket.error as e:
            self._connection_error(e)

            # (magic, opcode, keylen, extlen, datatype, status, bodylen, opaque, cas, extra_content)
            message = str(e)
            return (self.MAGIC['response'], -1, 0, 0, 0, self.STATUS['server_disconnected'], 0, 0, 0, message)
302969
def RequestPacket(self):
        
        attr = self._PktEncodeAttributes()

        if self.authenticator is None:
            self.authenticator = self.CreateAuthenticator()

        if self.id is None:
            self.id = self.CreateID()

        header = struct.pack('!BBH16s', self.code, self.id,
            (20 + len(attr)), self.authenticator)

        return header + attr
535607
public final HttpServer cookieCodec(ServerCookieEncoder encoder) {
		ServerCookieDecoder decoder = encoder == ServerCookieEncoder.LAX ?
				ServerCookieDecoder.LAX : ServerCookieDecoder.STRICT;
		return tcpConfiguration(tcp -> tcp.bootstrap(
				b -> HttpServerConfiguration.cookieCodec(b, encoder, decoder)));
	}
1251520
def cookies(self) -> Mapping[str, str]:
        
        raw = self.headers.get(hdrs.COOKIE, '')
        parsed = SimpleCookie(raw)
        return MappingProxyType(
            {key: val.value for key, val in parsed.items()})
195515
private String getRealm(String sUrl) throws IOException, ModuleException
   {

      AuthorizationHandler ah = AuthorizationInfo.getAuthHandler();

      try
      {
         URL url = new URL(sUrl);
         HTTPConnection connection = new HTTPConnection(url);
         connection.removeModule(CookieModule.class);
         AuthorizationInfo.setAuthHandler(null);

         HTTPResponse resp = connection.Get(url.getFile());

         String authHeader = resp.getHeader("WWW-Authenticate");
         if (authHeader == null)
         {
            return null;
         }

         String realm = authHeader.split("=")[1];
         realm = realm.substring(1, realm.length() - 1);

         return realm;

      }
      finally
      {
         AuthorizationInfo.setAuthHandler(ah);
      }
   }
142852
def _polling_cookie(self):
        
        parsed_url = urlparse(self._response.request.url)
        host = parsed_url.hostname.strip('.')
        if host == 'localhost':
            return {'cookie': self._response.headers.get('set-cookie', '')}
        return {}
123827
def go_to_py_cookie(go_cookie):
    ''''''
    expires = None
    if go_cookie.get('Expires') is not None:
        t = pyrfc3339.parse(go_cookie['Expires'])
        expires = t.timestamp()
    return cookiejar.Cookie(
        version=0,
        name=go_cookie['Name'],
        value=go_cookie['Value'],
        port=None,
        port_specified=False,
        # Unfortunately Python cookies don't record the original
        # host that the cookie came from, so we'll just use Domain
        # for that purpose, and record that the domain was specified,
        # even though it probably was not. This means that
        # we won't correctly record the CanonicalHost entry
        # when writing the cookie file after reading it.
        domain=go_cookie['Domain'],
        domain_specified=not go_cookie['HostOnly'],
        domain_initial_dot=False,
        path=go_cookie['Path'],
        path_specified=True,
        secure=go_cookie['Secure'],
        expires=expires,
        discard=False,
        comment=None,
        comment_url=None,
        rest=None,
        rfc2109=False,
    )
722156
def RequestPacket(self):
        

        attr = self._PktEncodeAttributes()

        if self.id is None:
            self.id = self.CreateID()

        header = struct.pack('!BBH', self.code, self.id, (20 + len(attr)))
        self.authenticator = md5_constructor(header[0:4] + 16 * six.b('\x00') + attr
            + self.secret).digest()
        return header + self.authenticator + attr