User-Agent Header. Sends library identification to Azure endpoint.
547000
def get_user_agent():
    '''
    '''
    version = pkg_resources.require("azurerm")[0].version
    user_agent = "python/{} ({}) requests/{} azurerm/{}".format(
        platform.python_version(),
        platform.platform(),
        requests.__version__,
        version)
    return user_agent
1368222
def get_auth_header(self):
        
        if self.api.is_authenticated:
            return {"Authorization": "Bearer %s" % self.api.access_token}
        return {"Authorization": "Client-ID %s" % self.api.client_id}
439075
def _get_user_agent(self):
        
        user_agent = request.headers.get('User-Agent')
        if user_agent:
            user_agent = user_agent.encode('utf-8')
        return user_agent or ''
626490
def format_endpoint(schema, addr, port, api_version):
    
    return '{}://{}:{}/{}/'.format(schema, addr, port,
                                   get_api_suffix(api_version))
500438
def __SetBaseHeaders(self, http_request, client):
        """"""
        # TODO(craigcitro): Make the default a little better here, and
        # include the apitools version.
        user_agent = client.user_agent or 'apitools-client/1.0'
        http_request.headers['user-agent'] = user_agent
        http_request.headers['accept'] = 'application/json'
        http_request.headers['accept-encoding'] = 'gzip, deflate'
1027912
def update(self, eid, data, token):
        
        final_dict = {"data": {"id": eid, "type": "libraryEntries", "attributes": data}}
        final_headers = self.header
        final_headers['Authorization'] = "Bearer {}".format(token)

        r = requests.patch(self.apiurl + "/library-entries/{}".format(eid), json=final_dict, headers=final_headers)

        if r.status_code != 200:
            raise ConnectionError(r.text)

        return True
1035745
def api_user(request, userPk, key=None, hproPk=None):
    """"""

    if not check_api_key(request, key, hproPk):
        return HttpResponseForbidden

    if settings.PIAPI_STANDALONE:
        if not settings.PIAPI_REALUSERS:
            user = generate_user(pk=userPk)
            if user is None:
                return HttpResponseNotFound()
        else:
            user = get_object_or_404(DUser, pk=userPk)

        hproject = None
    else:
        from users.models import TechUser

        user = get_object_or_404(TechUser, pk=userPk)

        (_, _, hproject) = getPlugItObject(hproPk)

        user.ebuio_member = hproject.isMemberRead(user)
        user.ebuio_admin = hproject.isMemberWrite(user)
        user.subscription_labels = _get_subscription_labels(user, hproject)

    retour = {}

    # Append properties for the user data
    for prop in settings.PIAPI_USERDATA:
        if hasattr(user, prop):
            retour[prop] = getattr(user, prop)

    retour['id'] = str(retour['pk'])

    # Append the users organisation and access levels
    orgas = {}
    if user:
        limitedOrgas = []

        if hproject and hproject.plugItLimitOrgaJoinable:
            # Get List of Plugit Available Orgas first
            projectOrgaIds = hproject.plugItOrgaJoinable.order_by('name').values_list('pk', flat=True)
            for (orga, isAdmin) in user.getOrgas(distinct=True):
                if orga.pk in projectOrgaIds:
                    limitedOrgas.append((orga, isAdmin))
        elif hasattr(user, 'getOrgas'):
            limitedOrgas = user.getOrgas(distinct=True)

        # Create List
        orgas = [{'id': orga.pk, 'name': orga.name, 'codops': orga.ebu_codops, 'is_admin': isAdmin} for (orga, isAdmin)
                 in limitedOrgas]
    retour['orgas'] = orgas

    return HttpResponse(json.dumps(retour), content_type="application/json")
580634
private void applyUserAgent(PutMediaRequest request, Request<PutMediaRequest> marshalled) {
        if (!marshalled.getHeaders().containsKey("User-Agent")) {
            marshalled.addHeader("User-Agent",
                                 RuntimeHttpUtils.getUserAgent(new ClientConfiguration(),
                                                               request.getRequestClientOptions()
                                                                      .getClientMarker(RequestClientOptions.Marker.USER_AGENT)));
        }
    }
1123399
def _api_call(self, endpoint, model=None, method=None, data=None, filters=None):
        
        if not self.token:
            raise RuntimeError("You do not have an API token!")

        if not method:
            raise ValueError("Method is required for API calls!")

        if model:
            endpoint = endpoint.format(**vars(model))
        url = '{}{}'.format(self.base_url, endpoint)
        headers = {
            'Authorization': "Bearer {}".format(self.token),
            'Content-Type': 'application/json',
            'User-Agent': self._user_agent,
        }

        if filters:
            headers['X-Filter'] = json.dumps(filters)

        body = None
        if data is not None:
            body = json.dumps(data)

        response = method(url, headers=headers, data=body)

        warning = response.headers.get('Warning', None)
        if warning:
            logger.warning('Received warning from server: {}'.format(warning))

        if 399 < response.status_code < 600:
            j = None
            error_msg = '{}: '.format(response.status_code)
            try:
                j = response.json()
                if 'errors' in j.keys():
                    for e in j['errors']:
                        error_msg += '{}; '.format(e['reason']) \
                                if 'reason' in e.keys() else ''
            except:
                pass
            raise ApiError(error_msg, status=response.status_code, json=j)

        if response.status_code != 204:
            j = response.json()
        else:
            j = None # handle no response body

        return j
1342511
private LibraryPolicyAuditResponse getLibraryPolicyAuditResponse(CollectorItem collectorItem, long beginDate, long endDate) {
        List<LibraryPolicyResult> libraryPolicyResults = libraryPolicyResultsRepository.findByCollectorItemIdAndEvaluationTimestampIsBetweenOrderByTimestampDesc(collectorItem.getId(), beginDate - 1, endDate + 1);

        LibraryPolicyAuditResponse libraryPolicyAuditResponse = new LibraryPolicyAuditResponse();

        if (CollectionUtils.isEmpty(libraryPolicyResults)) {
            libraryPolicyAuditResponse.addAuditStatus(LibraryPolicyAuditStatus.LIBRARY_POLICY_AUDIT_MISSING);
            return libraryPolicyAuditResponse;
        }

        LibraryPolicyResult returnPolicyResult = libraryPolicyResults.get(0);
        libraryPolicyAuditResponse.setLibraryPolicyResult(returnPolicyResult);
        libraryPolicyAuditResponse.setLastExecutionTime(returnPolicyResult.getEvaluationTimestamp());

        //threats by type
        Set<LibraryPolicyResult.Threat> securityThreats = !MapUtils.isEmpty(returnPolicyResult.getThreats()) ? returnPolicyResult.getThreats().get(LibraryPolicyType.Security) : SetUtils.EMPTY_SET;
        Set<LibraryPolicyResult.Threat> licenseThreats = !MapUtils.isEmpty(returnPolicyResult.getThreats()) ? returnPolicyResult.getThreats().get(LibraryPolicyType.License) : SetUtils.EMPTY_SET;


        boolean isOk = true;
        //License Threats
        if (licenseThreats.stream().anyMatch(threat -> Objects.equals(threat.getLevel(), LibraryPolicyThreatLevel.Critical) && hasViolations(threat))) {
            libraryPolicyAuditResponse.addAuditStatus(LibraryPolicyAuditStatus.LIBRARY_POLICY_FOUND_CRITICAL_LICENSE);
            isOk = false;
        }

        if (licenseThreats.stream().anyMatch(threat -> Objects.equals(threat.getLevel(), LibraryPolicyThreatLevel.High) && hasViolations(threat))) {
            libraryPolicyAuditResponse.addAuditStatus(LibraryPolicyAuditStatus.LIBRARY_POLICY_FOUND_HIGH_LICENSE);
            isOk = false;
        }

        //Security Threats
        if (securityThreats.stream().anyMatch(threat -> Objects.equals(threat.getLevel(), LibraryPolicyThreatLevel.Critical) && hasViolations(threat))) {
            libraryPolicyAuditResponse.addAuditStatus(LibraryPolicyAuditStatus.LIBRARY_POLICY_FOUND_CRITICAL_SECURITY);
            isOk = false;
        }

        if (securityThreats.stream().anyMatch(threat -> Objects.equals(threat.getLevel(), LibraryPolicyThreatLevel.High) && hasViolations(threat))) {
            libraryPolicyAuditResponse.addAuditStatus(LibraryPolicyAuditStatus.LIBRARY_POLICY_FOUND_HIGH_SECURITY);
            isOk = false;
        }

        if (isOk) {
            libraryPolicyAuditResponse.addAuditStatus(LibraryPolicyAuditStatus.LIBRARY_POLICY_AUDIT_OK);
        }

        return libraryPolicyAuditResponse;
    }
223946
def grant_client(self, client_id, publish=False, subscribe=False, publish_protocol=None, publish_topics=None,
                     subscribe_topics=None, scope_prefix='predix-event-hub', **kwargs):
        
        scopes = ['openid']
        authorities = ['uaa.resource']

        zone_id = self.get_zone_id()
        # always must be part of base user scope
        scopes.append('%s.zones.%s.user' % (scope_prefix, zone_id))
        authorities.append('%s.zones.%s.user' % (scope_prefix, zone_id))

        if publish_topics is not None or subscribe_topics is not None:
            raise Exception("multiple topics are not currently available in preidx-py")

        if publish_topics is None:
            publish_topics = ['topic']

        if subscribe_topics is None:
            subscribe_topics = ['topic']

        if publish:
            # we are granting just the default topic
            if publish_protocol is None:
                scopes.append('%s.zones.%s.grpc.publish' % (scope_prefix, zone_id))
                authorities.append('%s.zones.%s.grpc.publish' % (scope_prefix, zone_id))
                scopes.append('%s.zones.%s.wss.publish' % (scope_prefix, zone_id))
                authorities.append('%s.zones.%s.wss.publish' % (scope_prefix, zone_id))

            else:
                scopes.append('%s.zones.%s.%s.publish' % (scope_prefix, zone_id, publish_protocol))
                authorities.append('%s.zones.%s.%s.publish' % (scope_prefix, zone_id, publish_protocol))

            # we are requesting multiple topics
            for topic in publish_topics:
                if publish_protocol is None:
                    scopes.append('%s.zones.%s.%s.grpc.publish' % (scope_prefix, zone_id, topic))
                    scopes.append('%s.zones.%s.%s.wss.publish' % (scope_prefix, zone_id, topic))
                    scopes.append('%s.zones.%s.%s.user' % (scope_prefix, zone_id, topic))
                    authorities.append('%s.zones.%s.%s.grpc.publish' % (scope_prefix, zone_id, topic))
                    authorities.append('%s.zones.%s.%s.wss.publish' % (scope_prefix, zone_id, topic))
                    authorities.append('%s.zones.%s.%s.user' % (scope_prefix, zone_id, topic))
                else:
                    scopes.append('%s.zones.%s.%s.%s.publish' % (scope_prefix, zone_id, topic, publish_protocol))
                    authorities.append('%s.zones.%s.%s.%s.publish' % (scope_prefix, zone_id, topic, publish_protocol))
        if subscribe:
            # we are granting just the default topic
            scopes.append('%s.zones.%s.grpc.subscribe' % (scope_prefix, zone_id))
            authorities.append('%s.zones.%s.grpc.subscribe' % (scope_prefix, zone_id))

            # we are requesting multiple topics
            for topic in subscribe_topics:
                scopes.append('%s.zones.%s.%s.grpc.subscribe' % (scope_prefix, zone_id, topic))
                authorities.append('%s.zones.%s.%s.grpc.subscribe' % (scope_prefix, zone_id, topic))

        self.service.uaa.uaac.update_client_grants(client_id, scope=scopes,
                                                   authorities=authorities)

        return self.service.uaa.uaac.get_client(client_id)
326509
def api_user_uuid(request, userUuid, key=None, hproPk=None):
    """"""

    if not check_api_key(request, key, hproPk):
        return HttpResponseForbidden

    # From UUID to Pk
    from users.models import TechUser

    user = get_object_or_404(TechUser, uuid=userUuid)

    (_, _, hproject) = getPlugItObject(hproPk)

    user.ebuio_member = hproject.isMemberRead(user)
    user.ebuio_admin = hproject.isMemberWrite(user)
    user.subscription_labels = _get_subscription_labels(user, hproject)

    return api_user(request, user.pk, key, hproPk)
88743
private void notifyHandlers(ApiUser apiUser) {
        for(ServerUserHandlerClass handler : serverUserEventHandler) {
            Object userAgent = checkUserAgent(handler, apiUser);
            ReflectMethodUtil.invokeHandleMethod(
                    handler.getHandleMethod(), 
                    handler.newInstance(), 
                    context, 
                    userAgent);
        }
    }
747942
def to_header(self):
        """"""
        d = dict(self)
        auth_type = d.pop("__auth_type__", None) or "basic"
        return "%s %s" % (
            auth_type.title(),
            ", ".join(
                [
                    "%s=%s"
                    % (
                        key,
                        quote_header_value(
                            value, allow_token=key not in self._require_quoting
                        ),
                    )
                    for key, value in iteritems(d)
                ]
            ),
        )
409322
def _get_headers(self):
        """"""
        headers = {
            'user-agent': 'IPinfoClient/Python{version}/1.0'.format(version=sys.version_info[0]),
            'accept': 'application/json'
        }

        if self.access_token:
            headers['authorization'] = 'Bearer {}'.format(self.access_token)

        return headers
1074007
def requestPdpContextActivation(AccessPointName_presence=0):
    """"""
    a = TpPd(pd=0x8)
    b = MessageType(mesType=0x44)  # 01000100
    c = PacketDataProtocolAddress()
    packet = a / b / c
    if AccessPointName_presence is 1:
        d = AccessPointName(ieiAPN=0x28)
        packet = packet / d
    return packet
1363611
def _construct_request(self):
        
        if self.parsed_endpoint.scheme == 'https':
            conn = httplib.HTTPSConnection(self.parsed_endpoint.netloc)
        else:
            conn = httplib.HTTPConnection(self.parsed_endpoint.netloc)
        head = {
            "Accept": "application/json",
            "User-Agent": USER_AGENT,
            API_TOKEN_HEADER_NAME: self.api_token,
        }
        if self.api_version in ['0.1', '0.01a']:
            head[API_VERSION_HEADER_NAME] = self.api_version
        return conn, head