def api_dataset_view(request, DataSet_UKCL, root_id, response_format):
    '''
        it returns the data of the istance with pk=root_id in the dataset (which is a view)
        if we are browsing a view there is not just one single root that we can explore
        but a list of instances that match the criteria; root_id tells us which one to browse
        CAN BE CACHED
    '''
    response_format = response_format.upper()
    DataSet_UKCL_decoded = urllib.parse.unquote(DataSet_UKCL).replace("%2F","/")
    dataset = DataSet.retrieve_locally(DataSet_UKCL_decoded)
    actual_instance = ""
    actual_instance_json = ""
    # this dataset is a view; I shall use root_id to retrieve the actual instance
    module_name = dataset.dataset_structure.root_node.model_metadata.module
    dataset_uri = KsUrl(DataSet_UKCL_decoded)
    actual_instance_class = OrmWrapper.load_class(dataset_uri.netloc, module_name, dataset.dataset_structure.root_node.model_metadata.name) 
    actual_instance = actual_instance_class.objects.get(pk=root_id)
    
    if response_format == 'HTML' or response_format == 'BROWSE':
        actual_instance_json = '{' + actual_instance.serialize(dataset.dataset_structure.root_node, export_format='json', exported_instances = []) + '}'
    if response_format == 'JSON':
        ar = ApiResponse()
        ar.content = { "DataSet": dataset.export(export_format = 'DICT') }
        ar.status = ApiResponse.success
        return render(request, 'knowledge_server/export.json', {'json': ar.json()}, content_type="application/json")
    if response_format == 'XML':
        ar = ApiResponse()
        ar.status = ApiResponse.success
        ar.content = dataset.export(export_format = response_format)
        return render(request, 'knowledge_server/export.xml', {'xml': ar.xml()}, content_type="application/xhtml+xml")
    if response_format == 'HTML' or response_format == 'BROWSE':
        this_ks = KnowledgeServer.this_knowledge_server()
        cont = RequestContext(request, {'dataset': dataset, 'actual_instance': actual_instance, 'actual_instance_json': actual_instance_json, 'sn': dataset.dataset_structure.root_node, 'DataSet_UKCL': DataSet_UKCL, 'this_ks':this_ks, 'this_ks_encoded_url':this_ks.url(True)})
        return render_to_response('knowledge_server/browse_dataset.html', context_instance=cont)
def api_dataset_view(request):
    '''
        it returns the data of the istance with pk=root_id in the dataset (which is a view)
        if we are browsing a view there is not just one single root that we can explore
        but a list of instances that match the criteria; root_id tells us which one to browse
        CAN BE CACHED
    '''
    DataSet_UKCL = request.GET['UKCL']
    root_id = request.GET['id']
    ar = ApiResponse(request=request)

    dataset = DataSet.retrieve_locally(DataSet_UKCL)
    actual_instance = ""
    actual_instance_json = ""
    # this dataset is a view; I shall use root_id to retrieve the actual instance
    module_name = dataset.dataset_structure.root_node.model_metadata.module
    dataset_uri = KsUrl(DataSet_UKCL)
    actual_instance_class = OrmWrapper.load_class(
        dataset_uri.netloc, module_name,
        dataset.dataset_structure.root_node.model_metadata.name)
    actual_instance = actual_instance_class.objects.get(pk=root_id)

    if ar.response_format == 'HTML' or ar.response_format == 'BROWSE':
        actual_instance_json = '{' + actual_instance.serialize(
            dataset.dataset_structure.root_node,
            export_format='json',
            exported_instances=[]) + '}'
    if ar.response_format == 'JSON':
        ar.content = {"DataSet": dataset.export(export_format='DICT')}
        ar.status = ApiResponse.success
        return render(request,
                      'knowledge_server/export.json', {'json': ar.json()},
                      content_type="application/json")
    if ar.response_format == 'XML':
        ar.status = ApiResponse.success
        ar.content = dataset.export(export_format=ar.response_format)
        return render(request,
                      'knowledge_server/export.xml', {'xml': ar.xml()},
                      content_type="application/xhtml+xml")
    if ar.response_format == 'HTML' or ar.response_format == 'BROWSE':
        this_ks = KnowledgeServer.this_knowledge_server()
        cont = RequestContext(
            request, {
                'dataset': dataset,
                'actual_instance': actual_instance,
                'actual_instance_json': actual_instance_json,
                'sn': dataset.dataset_structure.root_node,
                'DataSet_UKCL': DataSet_UKCL,
                'this_ks': this_ks,
                'this_ks_encoded_url': this_ks.url(True)
            })
        return render_to_response('knowledge_server/browse_dataset.html',
                                  context_instance=cont)
def api_catch_all(request, uri_instance):
    '''
        parameters:
            url: http://root.beta.thekoa.org/knowledge_server/Attribute/1
            url: http://root.beta.thekoa.org/knowledge_server/Attribute/1/xml
            url: http://root.beta.thekoa.org/knowledge_server/Attribute/1/json
        
        Implementation:
            I do something only if it is a UKCL in my database; otherwise I return a not found message
            If there is a trailing string for the response_format I use it, otherwise I apply the default xml
            The trailing string can be "/xml", "/xml/", "/json", "/json/" where each character can 
            be either upper or lower case   
        CAN BE CACHED
    '''
    # I search for a response_format string, a UKCL has no trailing slash
    response_format = 'XML' #default
    if uri_instance[-1:] == "/":
        #I remove a trailing slash
        uri_instance = uri_instance[:-1]
    if uri_instance[-3:].lower() == "xml":
        uri_instance = uri_instance[:-4]
    if uri_instance[-4:].lower() == "json":
        response_format = 'JSON'
        uri_instance = uri_instance[:-5]
        
    try:
        split_path = uri_instance.split('/')
        if len(split_path) == 3:
            module_name = split_path[0]
            simple_entity_name = split_path[1]
            this_ks = KnowledgeServer.this_knowledge_server()
            actual_class = OrmWrapper.load_class(this_ks.netloc, module_name, simple_entity_name)
            instance = actual_class.retrieve_locally(this_ks.url() + "/" + uri_instance)
            if response_format == 'JSON':
                exported_json = '{ "Export" : { "ExportDateTime" : "' + str(datetime.now()) + '", ' + instance.serialize(export_format='JSON', exported_instances = []) + ' } }'
                return render(request, 'knowledge_server/export.json', {'json': exported_json}, content_type="application/json")
            if response_format == 'XML':
                exported_xml = "<Export ExportDateTime=\"" + str(datetime.now()) + "\">" + instance.serialize(export_format='XML', exported_instances = []) + "</Export>"
                xmldoc = minidom.parseString(exported_xml)
                exported_pretty_xml = xmldoc.toprettyxml(indent="    ")
                return render(request, 'knowledge_server/export.xml', {'xml': exported_pretty_xml}, content_type="application/xhtml+xml")
        else:
            raise(Exception("The url '" + uri_instance + "' does not match the UKCL format"))
    except Exception as es:
        if response_format == 'JSON':
            exported_json = '{ "Export" : { "ExportDateTime" : "' + str(datetime.now()) + '", "Error" : "' + str(es) + '" } }'
            return render(request, 'knowledge_server/export.json', {'json': exported_json}, content_type="application/json")
        if response_format == 'XML':
            exported_xml = "<Export ExportDateTime=\"" + str(datetime.now()) + "\" Error=\"" + str(es) + "\"/>"
            xmldoc = minidom.parseString(exported_xml)
            exported_pretty_xml = xmldoc.toprettyxml(indent="    ")
            return render(request, 'knowledge_server/export.xml', {'xml': exported_pretty_xml}, content_type="application/xhtml+xml")
def api_catch_all(request, uri_instance):
    '''
        parameters:
            url: http://root.beta.thekoa.org/knowledge_server/Attribute/1
            url: http://root.beta.thekoa.org/knowledge_server/Attribute/1/xml
            url: http://root.beta.thekoa.org/knowledge_server/Attribute/1/json
        
        Implementation:
            I do something only if it is a UKCL in my database; otherwise I return a not found message
            If there is a trailing string for the response_format I use it, otherwise I apply the default xml
            The trailing string can be "/xml", "/xml/", "/json", "/json/" where each character can 
            be either upper or lower case   
        CAN BE CACHED
    '''
    # I search for a response_format string, a UKCL has no trailing slash
    response_format = 'XML'  #default
    if uri_instance[-1:] == "/":
        #I remove a trailing slash
        uri_instance = uri_instance[:-1]
    if uri_instance[-3:].lower() == "xml":
        uri_instance = uri_instance[:-4]
    if uri_instance[-4:].lower() == "json":
        response_format = 'JSON'
        uri_instance = uri_instance[:-5]

    try:
        split_path = uri_instance.split('/')
        if len(split_path) == 3:
            module_name = split_path[0]
            simple_entity_name = split_path[1]
            this_ks = KnowledgeServer.this_knowledge_server()
            actual_class = OrmWrapper.load_class(this_ks.netloc, module_name,
                                                 simple_entity_name)
            instance = actual_class.retrieve_locally(this_ks.url() + "/" +
                                                     uri_instance)
            if response_format == 'JSON':
                exported_json = '{ "Export" : { "ExportDateTime" : "' + str(
                    datetime.now()) + '", ' + instance.serialize(
                        export_format='JSON', exported_instances=[]) + ' } }'
                return render(request,
                              'knowledge_server/export.json',
                              {'json': exported_json},
                              content_type="application/json")
            if response_format == 'XML':
                exported_xml = "<Export ExportDateTime=\"" + str(
                    datetime.now()) + "\">" + instance.serialize(
                        export_format='XML',
                        exported_instances=[]) + "</Export>"
                xmldoc = minidom.parseString(exported_xml)
                exported_pretty_xml = xmldoc.toprettyxml(indent="    ")
                return render(request,
                              'knowledge_server/export.xml',
                              {'xml': exported_pretty_xml},
                              content_type="application/xhtml+xml")
        else:
            raise (Exception("The url '" + uri_instance +
                             "' does not match the UKCL format"))
    except Exception as es:
        if response_format == 'JSON':
            exported_json = '{ "Export" : { "ExportDateTime" : "' + str(
                datetime.now()) + '", "Error" : "' + str(es) + '" } }'
            return render(request,
                          'knowledge_server/export.json',
                          {'json': exported_json},
                          content_type="application/json")
        if response_format == 'XML':
            exported_xml = "<Export ExportDateTime=\"" + str(
                datetime.now()) + "\" Error=\"" + str(es) + "\"/>"
            xmldoc = minidom.parseString(exported_xml)
            exported_pretty_xml = xmldoc.toprettyxml(indent="    ")
            return render(request,
                          'knowledge_server/export.xml',
                          {'xml': exported_pretty_xml},
                          content_type="application/xhtml+xml")