Queries Nexus for an artifact

    :param query_url: (str) Query URL
    :param timeout_sec: (int) query timeout
    :param basic_auth (HTTPBasicAuth) object or none
    :return: requests.Response object
    :raises: RuntimeError
973508
def query_nexus(query_url, timeout_sec, basic_auth=None):
    
    log = logging.getLogger(mod_logger + '.query_nexus')

    # Attempt to query Nexus
    retry_sec = 5
    max_retries = 6
    try_num = 1
    query_success = False
    nexus_response = None
    while try_num <= max_retries:
        if query_success:
            break
        log.debug('Attempt # {n} of {m} to query the Nexus URL: {u}'.format(n=try_num, u=query_url, m=max_retries))
        try:
            nexus_response = requests.get(query_url, auth=basic_auth, stream=True, timeout=timeout_sec)
        except requests.exceptions.Timeout:
            _, ex, trace = sys.exc_info()
            msg = '{n}: Nexus initial query timed out after {t} seconds:\n{e}'.format(
                n=ex.__class__.__name__, t=timeout_sec, r=retry_sec, e=str(ex))
            log.warn(msg)
            if try_num < max_retries:
                log.info('Retrying query in {t} sec...'.format(t=retry_sec))
                time.sleep(retry_sec)
        except (requests.exceptions.RequestException, requests.exceptions.ConnectionError):
            _, ex, trace = sys.exc_info()
            msg = '{n}: Nexus initial query failed with the following exception:\n{e}'.format(
                n=ex.__class__.__name__, r=retry_sec, e=str(ex))
            log.warn(msg)
            if try_num < max_retries:
                log.info('Retrying query in {t} sec...'.format(t=retry_sec))
                time.sleep(retry_sec)
        else:
            query_success = True
        try_num += 1

    if not query_success:
        msg = 'Unable to query Nexus after {m} attempts using URL: {u}'.format(
            u=query_url, m=max_retries)
        log.error(msg)
        raise RuntimeError(msg)

    if nexus_response.status_code != 200:
        msg = 'Nexus request returned code {c}, unable to query Nexus using URL: {u}'.format(
            u=query_url, c=nexus_response.status_code)
        log.error(msg)
        raise RuntimeError(msg)
    return nexus_response
581449
def login_handler(self, config=None, prefix=None, **args):
        
        headers = {}
        headers['Access-control-allow-origin'] = '*'
        headers['Content-type'] = 'text/html'
        auth = request.authorization
        if (auth and auth.username == auth.password):
            return self.set_cookie_close_window_response(
                "valid-http-basic-login")
        else:
            headers['WWW-Authenticate'] = (
                'Basic realm="HTTP-Basic-Auth at %s (u=p to login)"' %
                (self.name))
            return make_response("", 401, headers)
1104694
def auth_basic(check, realm="private", text="Access denied"):
    '''  '''
    def decorator(func):
        def wrapper(*a, **ka):
            user, password = request.auth or (None, None)
            if user is None or not check(user, password):
                err = HTTPError(401, text)
                err.add_header('WWW-Authenticate', 'Basic realm="%s"' % realm)
                return err
            return func(*a, **ka)
        return wrapper
    return decorator
781195
def query(params=None):
    '''
    
    '''
    path = 'https://ecs-cn-hangzhou.aliyuncs.com'

    access_key_id = config.get_cloud_config_value(
        'id', get_configured_provider(), __opts__, search_global=False
    )
    access_key_secret = config.get_cloud_config_value(
        'key', get_configured_provider(), __opts__, search_global=False
    )

    timestamp = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())

    # public interface parameters
    parameters = {
        'Format': 'JSON',
        'Version': DEFAULT_ALIYUN_API_VERSION,
        'AccessKeyId': access_key_id,
        'SignatureVersion': '1.0',
        'SignatureMethod': 'HMAC-SHA1',
        'SignatureNonce': six.text_type(uuid.uuid1()),
        'TimeStamp': timestamp,
    }

    # include action or function parameters
    if params:
        parameters.update(params)

    # Calculate the string for Signature
    signature = _compute_signature(parameters, access_key_secret)
    parameters['Signature'] = signature

    request = requests.get(path, params=parameters, verify=True)
    if request.status_code != 200:
        raise SaltCloudSystemExit(
            'An error occurred while querying aliyun ECS. HTTP Code: {0}  '
            'Error: \'{1}\''.format(
                request.status_code,
                request.text
            )
        )

    log.debug(request.url)

    content = request.text

    result = salt.utils.json.loads(content)
    if 'Code' in result:
        raise SaltCloudSystemExit(
            pprint.pformat(result.get('Message', {}))
        )
    return result
17177
def query(self, url, method="GET", params=dict(), headers=dict()):
        
        access_token = self._get_at_from_session()
        oauth = OAuth1(
            self.consumer_key,
            client_secret=self.secret_key,
            resource_owner_key=access_token['oauth_token'],
            resource_owner_secret=access_token['oauth_token_secret'])
        response = getattr(requests, method.lower())(url,
                                                     auth=oauth,
                                                     headers=headers,
                                                     params=params)
        if response.status_code != 200:
            raise OAuthError(
                _('No access to private resources at "%s".')
                % get_token_prefix(self.request_token_url))

        return response.text
728931
def query(method='GET', profile_dict=None, url=None, path='api/v1',
          action=None, api_key=None, service=None, params=None,
          data=None, subdomain=None, client_url=None, description=None,
          opts=None, verify_ssl=True):
    '''
    
    '''
    user_agent = 'SaltStack {0}'.format(__version__)

    if opts is None:
        opts = {}

    if isinstance(profile_dict, dict):
        creds = profile_dict
    else:
        creds = {}

    if api_key is not None:
        creds['pagerduty.api_key'] = api_key

    if service is not None:
        creds['pagerduty.service'] = service

    if subdomain is not None:
        creds['pagerduty.subdomain'] = subdomain

    if client_url is None:
        client_url = 'https://{0}.pagerduty.com'.format(
            creds['pagerduty.subdomain']
        )

    if url is None:
        url = 'https://{0}.pagerduty.com/{1}/{2}'.format(
            creds['pagerduty.subdomain'],
            path,
            action
        )

    if params is None:
        params = {}

    if data is None:
        data = {}

    data['client'] = user_agent

    # pagerduty.service is not documented.  While it makes sense to have in
    # some cases, don't force it when it is not defined.
    if 'pagerduty.service' in creds and creds['pagerduty.service'] is not None:
        data['service_key'] = creds['pagerduty.service']
    data['client_url'] = client_url
    if 'event_type' not in data:
        data['event_type'] = 'trigger'
    if 'description' not in data:
        if not description:
            data['description'] = 'SaltStack Event Triggered'
        else:
            data['description'] = description

    headers = {
        'User-Agent': user_agent,
        'Authorization': 'Token token={0}'.format(creds['pagerduty.api_key'])
    }
    if method == 'GET':
        data = {}
    else:
        headers['Content-type'] = 'application/json'

    result = salt.utils.http.query(
        url,
        method,
        params=params,
        header_dict=headers,
        data=salt.utils.json.dumps(data),
        decode=False,
        text=True,
        opts=opts,
    )

    return result['text']
1299374
def query(self,
              startTime=None,
              endTime=None,
              sinceServerStart=False,
              level="WARNING",
              services="*",
              machines="*",
              server="*",
              codes=[],
              processIds=[],
              export=False,
              exportType="CSV", #CSV or TAB
              out_path=None
              ):
        
        allowed_levels = ("SEVERE", "WARNING", "INFO",
                          "FINE", "VERBOSE", "DEBUG")
        qFilter = {
            "services": "*",
            "machines": "*",
            "server" : "*"
        }
        if len(processIds) > 0:
            qFilter['processIds'] = processIds
        if len(codes) > 0:
            qFilter['codes'] = codes
        params = {
            "f" : "json",
            "sinceServerStart" : sinceServerStart,
            "pageSize" : 10000
        }
        if startTime is not None and \
           isinstance(startTime, datetime):
            params['startTime'] = startTime.strftime("%Y-%m-%dT%H:%M:%S")
        if endTime is not None and \
           isinstance(endTime, datetime):
            params['endTime'] = endTime.strftime("%Y-%m-%dT%H:%M:%S")
        if level.upper() in allowed_levels:
            params['level'] = level
        if server != "*":
            qFilter['server'] = server.split(',')
        if services != "*":
            qFilter['services'] = services.split(',')
        if machines != "*":
            qFilter['machines'] = machines.split(",")
        params['filter'] = qFilter
        if export == True and \
           out_path is not None:
            messages = self._post(self._url + "/query", params,
                                     securityHandler=self._securityHandler,
                                     proxy_url=self._proxy_url,
                                     proxy_port=self._proxy_port)

            with open(name=out_path, mode='wb') as f:
                hasKeys = False
                if exportType == "TAB":
                    csvwriter = csv.writer(f, delimiter='\t')
                else:
                    csvwriter = csv.writer(f)
                for message in messages['logMessages']:
                    if hasKeys == False:
                        csvwriter.writerow(message.keys())
                        hasKeys = True
                    csvwriter.writerow(message.values())
                    del message
            del messages
            return out_path
        else:
            return self._post(self._url + "/query", params,
                                 securityHandler=self._securityHandler,
                                 proxy_url=self._proxy_url,
                                 proxy_port=self._proxy_port)
851722
def query(self, resource):
        
        if resource[0] in ['=', '@', '!']:  # Have no process for handling these
            raise ValueError('Not allowed resource identifier')

        try:
            part = urlsplit(resource)
        except Exception:
            raise ValueError('Unparsable resource')
        else:
            if not part[SCHEME]:
                if not part[NETLOC]:
                    _path = part[PATH]
                    if not part[QUERY] and not part[FRAGMENT]:
                        if '/' in _path or ':' in _path:
                            resource = "https://{}".format(resource)
                            part = urlsplit(resource)
                            authority = part[NETLOC]
                        else:
                            if '@' in _path:
                                authority = _path.split('@')[1]
                            else:
                                authority = _path
                            resource = 'acct:{}'.format(_path)
                    elif part[QUERY]:
                        resource = "https://{}?{}".format(_path, part[QUERY])
                        parts = urlsplit(resource)
                        authority = parts[NETLOC]
                    else:
                        resource = "https://{}".format(_path)
                        part = urlsplit(resource)
                        authority = part[NETLOC]
                else:
                    raise ValueError('Missing netloc')
            else:
                _scheme = part[SCHEME]
                if _scheme not in ['http', 'https', 'acct']:
                    # assume it to be a hostname port combo,
                    # eg. example.com:8080
                    resource = 'https://{}'.format(resource)
                    part = urlsplit(resource)
                    authority = part[NETLOC]
                    resource = self.create_url(part, [FRAGMENT])
                elif _scheme in ['http', 'https'] and not part[NETLOC]:
                    raise ValueError(
                        'No authority part in the resource specification')
                elif _scheme == 'acct':
                    _path = part[PATH]
                    for c in ['/', '?']:
                        _path = _path.split(c)[0]

                    if '@' in _path:
                        authority = _path.split('@')[1]
                    else:
                        raise ValueError(
                            'No authority part in the resource specification')
                    authority = authority.split('#')[0]
                    resource = self.create_url(part, [FRAGMENT])
                else:
                    authority = part[NETLOC]
                    resource = self.create_url(part, [FRAGMENT])

        location = WF_URL.format(authority)
        return oidc.WebFingerRequest(
            resource=resource, rel=OIC_ISSUER).request(location)
1165321
def get_securities(self, page=1, **filter_param):
        
        url_path = self._build_url_path(None, None)
        params = {'page': page}
        # the endpoints respond just fine to invaliid query params,
        # they just ignore them, but the the real value of the endpoints
        # is only revealed when using the filters, so let's not waste
        # requests on filters that don't do anything.
        if filter_param:
            query_filter = filter_param.popitem()
            if query_filter[0] in self.VALID_SECURITY_FILTERS:
                params[query_filter[0]] = query_filter[1]
            else:
                error_msg = 'Invalid filter param. Must be one of: {0}'.format(','.join(self.VALID_SECURITY_FILTERS))
                raise exceptions.PyChartsRequestException(error_msg)

        return self._get_data(url_path, params)
478618
def query(self, query, **kwargs):
        """"""
        if not self.connection:
            if not self.connect():
                return CasparResponse(500, "Unable to connect CasparCG server")

        query = query.strip()
        if kwargs.get("verbose", True):
            if not query.startswith("INFO"):
                logging.debug("Executing AMCP: {}".format(query))
        query += "\r\n"

        if PYTHON_VERSION >= 3:
            query = bytes(query.encode("utf-8"))
            delim = bytes("\r\n".encode("utf-8"))
        else:
            delim = "\r\n"

        try:
            self.connection.write(query)
            result = self.connection.read_until(delim).strip()
        except Exception:
            log_traceback()
            return CasparResponse(500, "Query failed")

        if PYTHON_VERSION >= 3:
            result = result.decode("UTF-8")

        if not result:
            return CasparResponse(500, "No result")

        try:
            if result[0:3] == "202":
                return CasparResponse(202, "No result")

            elif result[0:3] in ["201", "200"]:
                stat = int(result[0:3])
                result = decode_if_py3(self.connection.read_until(delim)).strip()
                return CasparResponse(stat, result)

            elif int(result[0:1]) > 3:
                stat = int(result[0:3])
                return CasparResponse(stat, result)
        except Exception:
            log_traceback()
            return CasparResponse(500, "Malformed result: {}".format(result))
        return CasparResponse(500, "Unexpected result: {}".format(result))
1123319
def query(self, query=None):
        
        if query is None:
            return self.url.query
        self.url.query = query
654476
def basicauth(self, realm = b'all', nofail = False):
        ""
        if b'authorization' in self.headerdict:
            auth = self.headerdict[b'authorization']
            auth_pair = auth.split(b' ', 1)
            if len(auth_pair) < 2:
                raise HttpInputException('Authorization header is malformed')
            if auth_pair[0].lower() == b'basic':
                try:
                    userpass = base64.b64decode(auth_pair[1])
                except Exception:
                    raise HttpInputException('Invalid base-64 string')
                userpass_pair = userpass.split(b':', 1)
                if len(userpass_pair) != 2:
                    raise HttpInputException('Authorization header is malformed')
                return userpass_pair
        if nofail:
            return (None, None)
        else:
            self.basicauthfail(realm)
758727
def basic_query(returns):
    """"""
    return compose(
        reusable,
        map_send(parse_request),
        map_yield(prepare_params, snug.prefix_adder(API_PREFIX)),
        map_return(loads(returns)),
        oneyield,
    )
885760
def _query(self, data_category, resource_category, field, request, step, isotime=None):
        
        rest_url = "/".join([HOST, data_category, resource_category, field, DATA_TYPE, request])
        query_string = "?" + "&".join(["res=" + step, "time=" + isotime if isotime is not None else "", "key=" + self.key])
        url = rest_url + query_string
        page = url_lib.urlopen(url)
        pg = page.read()
        return pg
749272
def query(self, query, variables=None, timeout=None, metadata=None,
              credentials=None):
        """"""
        new_metadata = self._dg.add_login_metadata(metadata)
        req = self._common_query(query, variables=variables)
        try:
            res = self._dc.query(req, timeout=timeout,
                                 metadata=new_metadata,
                                 credentials=credentials)
        except Exception as error:
            if util.is_jwt_expired(error):
                self._dg.retry_login()
                new_metadata = self._dg.add_login_metadata(metadata)
                res = self._dc.query(req, timeout=timeout,
                                     metadata=new_metadata,
                                     credentials=credentials)
            else:
                raise error

        self.merge_context(res.txn)
        return res
522254
def _query(action=None,
           command=None,
           args=None,
           method='GET',
           data=None):
    '''
    
    '''
    subdomain = __opts__.get('bamboohr', {}).get('subdomain', None)
    path = 'https://api.bamboohr.com/api/gateway.php/{0}/v1/'.format(
        subdomain
    )

    if action:
        path += action

    if command:
        path += '/{0}'.format(command)

    log.debug('BambooHR URL: %s', path)

    if not isinstance(args, dict):
        args = {}

    return_content = None
    result = salt.utils.http.query(
        path,
        method,
        username=_apikey(),
        password='saltypork',
        params=args,
        data=data,
        decode=False,
        text=True,
        status=True,
        opts=__opts__,
    )
    log.debug('BambooHR Response Status Code: %s', result['status'])

    return [result['status'], result['text']]
660862
def POST_query(self, req_hook, req_args):
        '''  '''
        # HTTP POST queries require keyManagerTokens and sessionTokens
        headers = {'Content-Type': 'application/json',
                   'sessionToken': self.__session__,
                   'keyManagerToken': self.__keymngr__}

        # HTTP POST query to keymanager authenticate API
        try:
            if req_args is None:
                response = requests.post(self.__url__ + req_hook,
                                         headers=headers,
                                         verify=True)
            else:
                response = requests.post(self.__url__ + req_hook,
                                         headers=headers,
                                         data=req_args,
                                         verify=True)
        except requests.exceptions.RequestException as err:
            self.logger.error(err)
            return '500', 'Internal Error in RESTful.POST_query()'
        # return the token
        return response.status_code, response.text