Use REQUEST_ID_HEADER if this is provided and looks like a UUID, if not allocate a random one.
769129
public static  UUID getOrCreateUserToken() {
        UUID userToken;
        if (Request.getPerThreadRequestData().getRequestId() != null) {
            try {
                userToken = UUID.fromString(Request.getPerThreadRequestData().getRequestId());
            } catch (final IllegalArgumentException ignored) {
                userToken = UUIDs.randomUUID();
            }
        } else {
            userToken = UUIDs.randomUUID();
        }
        return userToken;
    }
723206
def append_request_id(req, resp, resource, params):
    
    def get_headers(resp):
        if hasattr(resp, 'headers'):
            return resp.headers
        if hasattr(resp, '_headers'):
            return resp._headers
        return None

    if(isinstance(resp, Response) or
       (get_headers(resp) is not None)):
        # Extract 'x-request-id' from headers if
        # response is a Response object.
        request_id = get_headers(resp).get('x-request-id')
    else:
        # If resp is of type string or None.
        request_id = resp

    if resource.req_ids is None:
        resource.req_ids = []

    if request_id not in resource.req_ids:
        resource.req_ids.append(request_id)
824309
def remove_request(self, uuid):
        
        for key in list(self._request):
            if self._request[key] == uuid:
                del self._request[key]
966475
def random_str_uuid(string_length):
    """"""
    if not isinstance(string_length, int) or not 1 <= string_length <= 32:
        msg = "string_length must be type int where 1 <= string_length <= 32"
        raise ValueError(msg)
    random = str(uuid.uuid4()).upper().replace('-', '')
    return random[0:string_length]
1099015
def getICMByUUID(uuid: str):
    
    _metadata = ICMMetadata.query.filter_by(id=uuid).first().deserialize()
    del _metadata["model_id"]
    return jsonify(_metadata)
758660
def uuid_to_slug(uuid):
    
    if not isinstance(uuid, int):
        raise ArgumentError("Invalid id that is not an integer", id=uuid)

    if uuid < 0 or uuid > 0x7fffffff:
        # For now, limiting support to a signed integer (which on some platforms, can be 32bits)
        raise ArgumentError("Integer should be a positive number and smaller than 0x7fffffff", id=uuid)

    return '--'.join(['d', int64gid(uuid)])
1288369
def nice_identifier():
    ''
    big = reduce(mul, struct.unpack('<LLLL', os.urandom(16)), 1)
    big = big % 2**128
    return uuid.UUID(int=big).hex
974527
def uuid(self, value):
        """"""
        if value is not None:
            self.keystore['id'] = value
        elif 'id' in self.keystore:
            self.keystore.pop('id')
201936
def getClientUID(self):
        
        request = self.getRequest()
        if request:
            client = request.getClient()
            if client:
                return client.UID()
1358830
def __new_request_id(self):
        
        while True:
            # Since seqnum wraps on 2^64 at most, this should always fit into 32 chars (QAPI request id limit)
            with self.__seqnum_lock:
                requestId = "%s%d" % (self.__reqpre, self.__reqnum)
            self.__reqnum += 1
            if requestId not in self.__requests:
                break
            # in the unlikely event of a collision update prefix
            self.__reqpre = self.__rnd_string(6)
        return requestId
1011857
def request(self, method, params):
        """"""
        identifier = random.randint(1, 1000)
        self._transport.write(jsonrpc_request(method, identifier, params))
        self._buffer[identifier] = {'flag': asyncio.Event()}
        yield from self._buffer[identifier]['flag'].wait()
        result = self._buffer[identifier]['data']
        del self._buffer[identifier]['data']
        return result
14698
def uuid(self, name=None, pad_length=22):
        
        # If no name is given, generate a random UUID.
        if name is None:
            uuid = _uu.uuid4()
        elif "http" not in name.lower():
            uuid = _uu.uuid5(_uu.NAMESPACE_DNS, name)
        else:
            uuid = _uu.uuid5(_uu.NAMESPACE_URL, name)
        return self.encode(uuid, pad_length)
1217343
def add_headers(request)
      return if Logging.correlation_id.nil?
      request.add_field(CLIENT_REQUEST_ID.to_s, Logging.correlation_id)
      request.add_field(CLIENT_RETURN_CLIENT_REQUEST_ID.to_s, true)
    end
1354930
def post_generate_identifier(request):
    """"""
    d1_gmn.app.views.assert_db.post_has_mime_parts(request, (('field', 'scheme'),))
    if request.POST['scheme'] != 'UUID':
        raise d1_common.types.exceptions.InvalidRequest(
            0, 'Only the UUID scheme is currently supported'
        )
    fragment = request.POST.get('fragment', None)
    while True:
        pid = (fragment if fragment else '') + uuid.uuid4().hex
        if not d1_gmn.app.models.ScienceObject.objects.filter(pid__did=pid).exists():
            return pid
461393
def content_id(self) -> Optional[UnstructuredHeader]:
        """"""
        try:
            return cast(UnstructuredHeader, self[b'content-id'][0])
        except (KeyError, IndexError):
            return None
372545
def get_random_id(length):
    """"""
    alphabet = string.ascii_uppercase + string.ascii_lowercase + string.digits
    return ''.join(random.choice(alphabet) for _ in range(length))
122832
def make_uuid(cls, app_id=None):
        
        try:
            if app_id and isinstance(uuid.UUID(str(app_id), version=4), uuid.UUID):
                return str(app_id)
        except (ValueError, AssertionError):
            pass
        return str(uuid.UUID(int=random.getrandbits(128)))