'Handles given HTTP request.'

def HandleRequest(self, request):

    impersonated_username = config.CONFIG['AdminUI.debug_impersonate_user']
    if impersonated_username:
        logging.info('Overriding    user    as    %s', impersonated_username)
        request.user = config.CONFIG['AdminUI.debug_impersonate_user']
    if (not aff4_users.GRRUser.IsValidUsername(request.user)):
        return self._BuildResponse(403, dict(message=('Invalid    username:    %s' % request.user)))
    try:
        (router, method_metadata, args) = self._router_matcher.MatchRouter(request)
    except access_control.UnauthorizedAccess as e:
        logging.exception('Access    denied    to    %s    (%s):    %s', request.path, request.method, e)
        additional_headers = {'X-GRR-Unauthorized-Access-Reason': utils.SmartStr(e.message).replace('\n', ''), 'X-GRR-Unauthorized-Access-Subject': utils.SmartStr(e.subject)}
        return self._BuildResponse(403, dict(message=('Access    denied    by    ACL:    %s' % utils.SmartStr(e.message)), subject=utils.SmartStr(e.subject)), headers=additional_headers)
    except ApiCallRouterNotFoundError as e:
        return self._BuildResponse(404, dict(message=e.message))
    except werkzeug_exceptions.MethodNotAllowed as e:
        return self._BuildResponse(405, dict(message=e.message))
    except Error as e:
        logging.exception("Can't    match    URL    to    router/method:    %s", e)
        return self._BuildResponse(500, dict(message=str(e), traceBack=traceback.format_exc()))
    token = self.BuildToken(request, 60).SetUID()
    handler = None
    try:
        handler = getattr(router, method_metadata.name)(args, token=token)
        if (handler.args_type != method_metadata.args_type):
            raise RuntimeError(("Handler    args    type    doesn't    match    method    args    type:    %s    vs    %s" % (handler.args_type, method_metadata.args_type)))
        binary_result_type = api_call_router.RouterMethodMetadata.BINARY_STREAM_RESULT_TYPE
        if ((handler.result_type != method_metadata.result_type) and (not ((handler.result_type is None) and (method_metadata.result_type == binary_result_type)))):
            raise RuntimeError(("Handler    result    type    doesn't    match    method    result    type:    %s    vs    %s" % (handler.result_type, method_metadata.result_type)))
        if (request.method == 'HEAD'):
            if (method_metadata.result_type == method_metadata.BINARY_STREAM_RESULT_TYPE):
                binary_stream = handler.Handle(args, token=token)
                return self._BuildResponse(200, {'status': 'OK'}, method_name=method_metadata.name, no_audit_log=method_metadata.no_audit_log_required, content_length=binary_stream.content_length, token=token)
            else:
                return self._BuildResponse(200, {'status': 'OK'}, method_name=method_metadata.name, no_audit_log=method_metadata.no_audit_log_required, token=token)
        if (method_metadata.result_type == method_metadata.BINARY_STREAM_RESULT_TYPE):
            binary_stream = handler.Handle(args, token=token)
            return self._BuildStreamingResponse(binary_stream, method_name=method_metadata.name)
        else:
            format_mode = GetRequestFormatMode(request, method_metadata)
            result = self.CallApiHandler(handler, args, token=token)
            rendered_data = self._FormatResultAsJson(result, format_mode=format_mode)
            return self._BuildResponse(200, rendered_data, method_name=method_metadata.name, no_audit_log=method_metadata.no_audit_log_required, token=token)
    except access_control.UnauthorizedAccess as e:
        logging.exception('Access    denied    to    %s    (%s)    with    %s:    %s', request.path, request.method, method_metadata.name, e)
        additional_headers = {'X-GRR-Unauthorized-Access-Reason': utils.SmartStr(e.message).replace('\n', ''), 'X-GRR-Unauthorized-Access-Subject': utils.SmartStr(e.subject)}
        return self._BuildResponse(403, dict(message=('Access    denied    by    ACL:    %s' % e.message), subject=utils.SmartStr(e.subject)), headers=additional_headers, method_name=method_metadata.name, no_audit_log=method_metadata.no_audit_log_required, token=token)
    except api_call_handler_base.ResourceNotFoundError as e:
        return self._BuildResponse(404, dict(message=e.message), method_name=method_metadata.name, no_audit_log=method_metadata.no_audit_log_required, token=token)
    except NotImplementedError as e:
        return self._BuildResponse(501, dict(message=e.message), method_name=method_metadata.name, no_audit_log=method_metadata.no_audit_log_required, token=token)
    except Exception as e:
        logging.exception('Error    while    processing    %s    (%s)    with    %s:    %s', request.path, request.method, handler.__class__.__name__, e)
        return self._BuildResponse(500, dict(message=str(e), traceBack=traceback.format_exc()), method_name=method_metadata.name, no_audit_log=method_metadata.no_audit_log_required, token=token)
