def test_prepend_q_no(self):
        """ Check that ? is not added to front of parameters if required """

        pass_params = "?test=one&test=2&test=3"
        response = prepend_q(pass_params)

        expected = pass_params

        self.assertEquals(response, expected)
Ejemplo n.º 2
0
    def test_prepend_q_no(self):
        """ Check that ? is not added to front of parameters if required """

        pass_params = "?test=one&test=2&test=3"
        response = prepend_q(pass_params)

        expected = pass_params

        self.assertEquals(response, expected)
Ejemplo n.º 3
0
def fhir_conformance(request, via_oauth=False, v2=False, *args):
    """ Pull and filter fhir Conformance statement

    BaseStu3 = "CapabilityStatement"

    :param request:
    :param via_oauth:
    :param args:
    :param kwargs:
    :return:
    """
    crosswalk = None
    resource_router = get_resourcerouter()
    parsed_url = urlparse(resource_router.fhir_url)
    call_to = None
    if parsed_url.path is not None:
        call_to = '{}://{}/{}/fhir/metadata'.format(parsed_url.scheme,
                                                    parsed_url.netloc,
                                                    'v2' if v2 else 'v1')
    else:
        # url with no path
        call_to = '{}/{}/fhir/metadata'.format(resource_router.fhir_url,
                                               'v2' if v2 else 'v1')

    pass_params = {'_format': 'json'}

    encoded_params = urlencode(pass_params)
    pass_params = prepend_q(encoded_params)

    r = request_call(request, call_to + pass_params, crosswalk)

    text_out = ''

    if r.status_code >= 300:
        logger.debug("We have an error code to deal with: %s" % r.status_code)
        return HttpResponse(json.dumps(r._content),
                            status=r.status_code,
                            content_type='application/json')

    text_in = get_response_text(fhir_response=r)

    text_out = json.loads(text_in, object_pairs_hook=OrderedDict)

    od = conformance_filter(text_out)

    # Append Security to ConformanceStatement
    security_endpoint = build_oauth_resource(request, v2, format_type="json")
    od['rest'][0]['security'] = security_endpoint
    # Fix format values
    od['format'] = ['application/json', 'application/fhir+json']

    return JsonResponse(od)
Ejemplo n.º 4
0
def fhir_conformance(request, via_oauth=False, *args, **kwargs):
    """ Pull and filter fhir Conformance statement

    BaseStu3 = "CapabilityStatement"

    :param request:
    :param via_oauth:
    :param args:
    :param kwargs:
    :return:
    """
    crosswalk = None
    resource_router = get_resourcerouter()
    call_to = FhirServerUrl()

    if call_to.endswith('/'):
        call_to += 'metadata'
    else:
        call_to += '/metadata'

    pass_params = {'_format': 'json'}

    encoded_params = urlencode(pass_params)
    pass_params = prepend_q(encoded_params)

    r = request_call(request, call_to + pass_params, crosswalk)

    text_out = ''
    host_path = get_host_url(request, '?')

    if r.status_code >= 300:
        logger.debug("We have an error code to deal with: %s" % r.status_code)
        return HttpResponse(json.dumps(r._content),
                            status=r.status_code,
                            content_type='application/json')

    rewrite_url_list = build_rewrite_list(crosswalk)
    text_in = get_response_text(fhir_response=r)

    text_out = post_process_request(request, host_path, text_in,
                                    rewrite_url_list)

    od = conformance_filter(text_out, resource_router)

    # Append Security to ConformanceStatement
    security_endpoint = build_oauth_resource(request, format_type="json")
    od['rest'][0]['security'] = security_endpoint
    # Fix format values
    od['format'] = ['application/json', 'application/fhir+json']

    return JsonResponse(od)
Ejemplo n.º 5
0
def fhir_conformance(request, *args, **kwargs):
    """ Pull and filter fhir Conformance statement

    BaseDstu2 = "Conformance"
    BaseStu3 = "CapabilityStatement"

    metadata call

    """
    if not request.user.is_authenticated():
        return authenticated_home(request)

    try:
        cx = Crosswalk.objects.get(user=request.user)
    except Crosswalk.DoesNotExist:
        cx = None
        # logger.debug('Crosswalk for %s does not exist' % request.user)

    if cx:
        call_to = cx.fhir_source.fhir_url
    else:
        call_to = FhirServerUrl()

    resource_type = conformance_or_capability(call_to)

    if call_to.endswith('/'):
        call_to += 'metadata'
    else:
        call_to += '/metadata'

    pass_params = strip_oauth(request.GET)
    # pass_params should be an OrderedDict after strip_auth
    # logger.debug("result from strip_oauth:%s" % pass_params)

    # Let's store the inbound requested format
    # We need to simplify the format call to the backend
    # so that we get data we can manipulate
    requested_format = request_format(pass_params)

    # now we simplify the format/_format request for the back-end
    pass_params = strip_format_for_back_end(pass_params)
    back_end_format = pass_params['_format']

    encoded_params = urlencode(pass_params)
    #
    # Add ? to front of parameters if needed
    pass_params = prepend_q(encoded_params)

    # logger.debug("Calling:%s" % call_to + pass_params)

    ####################################################
    ####################################################

    r = request_call(request, call_to + pass_params, cx,
                     reverse_lazy('authenticated_home'))

    ####################################################
    ####################################################

    text_out = ''
    host_path = get_host_url(request, '?')

    # get 'xml' 'json' or ''
    # fmt = get_search_param_format(request.META['QUERY_STRING'])
    # force to json

    # logger.debug("Format:%s" % back_end_format)

    rewrite_url_list = settings.FHIR_SERVER_CONF['REWRITE_FROM']
    # print("Starting Rewrite_list:%s" % rewrite_url_list)

    text_out = post_process_request(request, back_end_format, host_path,
                                    r.text, rewrite_url_list)

    query_string = build_querystring(request.GET.copy())
    # logger.debug("Query:%s" % query_string)

    if 'xml' in requested_format:
        # logger.debug('We got xml back in od')

        # logger.debug("is xml filtered?%s" % requested_format)
        xml_dom = xml_to_dom(text_out)
        text_out = dom_conformance_filter(xml_dom)
        # logger.debug("Text from XML function:\n%s\n=========" % text_out)
        if 'html' not in requested_format:
            return HttpResponse(text_out,
                                content_type='application'
                                '/%s' % requested_format)
        else:
            # logger.debug("Sending text_out for display: %s" % text_out[0:100])
            return render(
                request, 'bluebutton/default_xml.html', {
                    'output': text_out,
                    'content': {
                        'parameters': query_string,
                        'resource_type': resource_type,
                        'request_method': "GET",
                        'interaction_type': "metadata",
                        'source': cx.fhir_source.name
                    }
                })

            # return HttpResponse( tostring(dict_to_xml('content', od)),
        #                      content_type='application/%s' % fmt)
    elif back_end_format == 'json':
        # logger.debug('We got json back in od')
        od = conformance_filter(text_out, back_end_format)
        text_out = pretty_json(od)
        if 'html' not in requested_format:
            return HttpResponse(text_out,
                                content_type='application/'
                                '%s' % requested_format)
    else:
        # let's make sure we have json to deliver:
        od = conformance_filter(text_out, back_end_format)
        text_out = pretty_json(od)

    # logger.debug('We got a different format:%s' % back_end_format)

    return render(
        request, 'bluebutton/default.html', {
            'output': text_out,
            'content': {
                'parameters': query_string,
                'resource_type': resource_type,
                'request_method': "GET",
                'interaction_type': "metadata",
                'source': cx.fhir_source.name
            }
        })
Ejemplo n.º 6
0
def fhir_conformance(request, *args, **kwargs):
    """ Pull and filter fhir Conformance statement

    metadata call

    """
    if not request.user.is_authenticated():
        return authenticated_home(request)

    resource_type = "Conformance"
    call_to = FhirServerUrl()
    if call_to.endswith("/"):
        call_to += "metadata"
    else:
        call_to += "/metadata"

    pass_params = urlencode(strip_oauth(request.GET))

    # Add ? to front of parameters if needed
    pass_params = prepend_q(pass_params)

    logger.debug("Calling:%s" % call_to + pass_params)

    r = request_call(request, call_to + pass_params, reverse_lazy("authenticated_home"))

    text_out = ""
    host_path = get_host_url(request, "?")

    # get 'xml' 'json' or ''
    fmt = get_search_param_format(request.META["QUERY_STRING"])

    rewrite_url_list = settings.FHIR_SERVER_CONF["REWRITE_FROM"]
    # print("Starting Rewrite_list:%s" % rewrite_url_list)

    text_out = post_process_request(request, fmt, host_path, r.text, rewrite_url_list)

    od = conformance_filter(text_out, fmt)

    if fmt == "xml":
        # logger.debug('We got xml back in od')
        return HttpResponse(text_out, content_type="application/%s" % fmt)
        # return HttpResponse( tostring(dict_to_xml('content', od)),
        #                      content_type='application/%s' % fmt)
    elif fmt == "json":
        # logger.debug('We got json back in od')
        return HttpResponse(pretty_json(od), content_type="application/%s" % fmt)

    # logger.debug('We got a different format:%s' % fmt)

    return render(
        request,
        "bluebutton/default.html",
        {
            "output": pretty_json(od),
            "content": {
                "parameters": request.GET.urlencode(),
                "resource_type": resource_type,
                "request_method": "GET",
                "interaction_type": "metadata",
            },
        },
    )
Ejemplo n.º 7
0
def metadata(request, via_oauth=False, *args, **kwargs):
    """
    Arrive here to do capabilityStatement or Conformance
    aka metadata

    oauth_fhir_conformance sets via_oauth=True
    fhir_conformance sets via_oauth=False

    :param request:
    :param via_oauth:
    :param args:
    :param kwargs:
    :return:
    """
    cx = None
    rr = get_resourcerouter()
    call_to = FhirServerUrl()

    resource_type = conformance_or_capability(call_to)

    if call_to.endswith('/'):
        call_to += 'metadata'
    else:
        call_to += '/metadata'

    pass_params = request.GET
    # pass_params should be an OrderedDict after strip_auth
    # logger.debug("result from strip_oauth:%s" % pass_params)

    # Let's store the inbound requested format
    # We need to simplify the format call to the backend
    # so that we get data we can manipulate
    requested_format = request_format(pass_params)

    # now we simplify the format/_format request for the back-end
    pass_params = strip_format_for_back_end(pass_params)
    back_end_format = pass_params['_format']

    encoded_params = urlencode(pass_params)
    #
    # Add ? to front of parameters if needed
    pass_params = prepend_q(encoded_params)

    # logger.debug("Calling:%s" % call_to + pass_params)

    query_string = build_querystring(request.GET.copy())

    ####################################################
    ####################################################

    r = request_call(request,
                     call_to + pass_params,
                     cx,
                     reverse_lazy('authenticated_home'))

    ####################################################
    ####################################################

    text_out = ''
    host_path = get_host_url(request, '?')

    if r.status_code in ERROR_CODE_LIST:
        logger.debug("We have an error code to deal with: %s" % r.status_code)
        if 'html' in requested_format.lower():
            return render(
                request,
                'bluebutton/default.html',
                {'output': pretty_json(r._content, indent=4),
                 'fhir_id': get_fhir_id(cx),
                 'content': {'parameters': query_string,
                             'resource_type': resource_type,
                             'id': id,
                             'request_method': "GET",
                             'interaction_type': "search",
                             'div_texts': "",
                             'source': get_fhir_source_name(cx)}})
        else:
            return HttpResponse(json.dumps(r._content, indent=4),
                                status=r.status_code,
                                content_type='application/json')

    # get 'xml' 'json' or ''
    # fmt = get_search_param_format(request.META['QUERY_STRING'])
    # force to json

    # logger.debug("Format:%s" % back_end_format)

    rewrite_url_list = build_rewrite_list(cx)
    # print("Starting Rewrite_list:%s" % rewrite_url_list)

    text_in = get_response_text(fhir_response=r)
    # print("Capability text: %s\n" % r.text)
    # print("Capability _text: %s\n" % r._text)

    # text_in = r.text
    # if text_in == "":
    #     print("Capability assigning _text: %s\n" % r._text[:100])
    #
    #     text_in = r._text

    text_out = post_process_request(request,
                                    back_end_format,
                                    host_path,
                                    text_in,
                                    rewrite_url_list)
    # define query string further up before request_call
    # query_string = build_querystring(request.GET.copy())

    # logger.debug("Query:%s" % query_string)

    if 'xml' in requested_format:
        # logger.debug('We got xml back in od')

        # logger.debug("is xml filtered?%s" % requested_format)
        xml_dom = xml_to_dom(text_out)

        text_out = dom_conformance_filter(xml_dom, rr)

        # Append Security to ConformanceStatement
        security_endpoint = build_oauth_resource(request,
                                                 format_type="xml")
        text_out = append_security(text_out,
                                   security_endpoint)

        # logger.debug("Text from XML function:\n%s\n=========" % text_out)
        if 'html' not in requested_format:
            return HttpResponse(text_out,
                                content_type='application'
                                             '/%s' % requested_format)
        else:
            # logger.debug("Sending text_out for display: %s" % text_out[0:100])
            return render(
                request,
                'bluebutton/default_xml.html',
                {'output': text_out,
                 'content': {'parameters': query_string,
                             'resource_type': resource_type,
                             'request_method': "GET",
                             'interaction_type': "metadata",
                             'source': get_fhir_source_name(cx)}})

            # return HttpResponse( tostring(dict_to_xml('content', od)),
        #                      content_type='application/%s' % fmt)
    else:
        # back_end_format == 'json'
        # logger.debug('We got json back in od')
        od = conformance_filter(text_out, back_end_format, rr)

        # Append Security to ConformanceStatement
        security_endpoint = build_oauth_resource(request,
                                                 format_type="json")
        print("OD:\n%s" % od['rest'])
        od['rest'][0]['security'] = security_endpoint
        print("OD+Security:\n%s" % od)

        text_out = pretty_json(od)
        if 'html' not in requested_format:
            return HttpResponse(text_out,
                                content_type='application/'
                                             '%s' % requested_format)
        if 'security' in od:
            print("%s" % pretty_json(od['security'], indent=4))
        else:
            print("No security content in Conformance")
            print("od: %s" % pretty_json(od, indent=4))

    # logger.debug('We got a different format:%s' % back_end_format)

    return render(
        request,
        'bluebutton/default.html',
        {'output': text_out,
         'content': {'parameters': query_string,
                     'resource_type': resource_type,
                     'request_method': "GET",
                     'interaction_type': "metadata"}})