def test_update_unpublish(self):
     id = self.createXMLData(ispublished=True)
     self.assertEquals(True, XMLdata.get(id)['ispublished'])
     url = '/dashboard/update_unpublish'
     data = {'result_id': str(id)}
     r = self.doRequestGetAdminClientLogged(url=url, data=data)
     self.assertEquals(False, XMLdata.get(id)['ispublished'])
 def test_update_publish_draft(self):
     status = Status.ACTIVE
     new_xml = "<Resource localid='' status='"+status+"'><identity>" \
            "<title>My new software</title></identity><curation><publisher>PF</publisher><contact><name></name>" \
            "</contact></curation><content><description>This is a new record</description><subject></subject>" \
            "<referenceURL></referenceURL></content></Resource>"
     id = self.createXMLData(ispublished=True)
     xmlData = XMLdata.get(id)
     self.assertNotEquals(new_xml, XMLdata.unparse(xmlData['content']))
     adminId = self.getAdmin().id
     template = self.createTemplate()
     elements = SchemaElement.objects().all()
     self.assertEqual(len(elements), 0)
     elementsForm = FormData.objects().all()
     self.assertEqual(len(elementsForm), 0)
     formData = self.createFormData(user=adminId, name='name', template=str(template.id), xml_data=new_xml,
                                    xml_data_id=str(id))
     url = '/dashboard/update_publish_draft'
     data = {'draft_id': str(formData.id)}
     r = self.doRequestGetAdminClientLogged(url=url, data=data)
     xmlDataInDatabase = XMLdata.get(id)
     elements = SchemaElement.objects().all()
     self.assertEqual(len(elements), 0)
     elementsForm = FormData.objects().all()
     self.assertEqual(len(elementsForm), 0)
     self.assertEquals(etree.XML(new_xml).text, etree.XML(str(XMLdata.unparse(xmlDataInDatabase['content']))).text)
     self.assertEquals(True, xmlDataInDatabase.get('ispublished'))
     self.assertEquals(str(adminId), xmlDataInDatabase.get('iduser'))
     self.assertNotEquals(xmlData.get('lastmodificationdate'), xmlDataInDatabase.get('lastmodificationdate'))
     self.assertNotEquals(xmlData.get('publicationdate'), xmlDataInDatabase.get('publicationdate'))
     self.assertEquals(status, xmlDataInDatabase.get('status'))
 def test_delete_result(self):
     id = self.createXMLData()
     self.assertIsNotNone(XMLdata.get(id))
     url = '/dashboard/delete_result'
     data = {'result_id': str(id)}
     r = self.doRequestGetAdminClientLogged(url=url, data=data)
     self.assertIsNone(XMLdata.get(id))
Esempio n. 4
0
 def test_change_owner_record(self):
     userId = self.getUser().id
     adminId = self.getAdmin().id
     template = self.createTemplate()
     xmldataid = self.createXMLData(iduser=userId, schemaID=template.id)
     self.assertEquals(str(userId), str(XMLdata.get(xmldataid)['iduser']))
     url = '/dashboard/change-owner-record'
     data = {'recordID': str(xmldataid), 'userID': str(adminId)}
     r = self.doRequestPostUserClientLogged(url=url, data=data)
     self.assertEquals(str(adminId), str(XMLdata.get(xmldataid)['iduser']))
     self.isStatusOK(r.status_code)
 def test_change_owner_record(self):
     userId = self.getUser().id
     adminId = self.getAdmin().id
     template = self.createTemplate()
     xmldataid = self.createXMLData(iduser=userId, schemaID=template.id)
     self.assertEquals(str(userId), str(XMLdata.get(xmldataid)['iduser']))
     url = '/dashboard/change-owner-record'
     data = {'recordID': str(xmldataid), 'userID': str(adminId)}
     r = self.doRequestPostUserClientLogged(url=url, data=data)
     self.assertEquals(str(adminId), str(XMLdata.get(xmldataid)['iduser']))
     self.isStatusOK(r.status_code)
def curate_enter_data(request):
    print "BEGIN curate_enter_data(request)"

    try:
        context = RequestContext(request, {})
        if 'id' in request.GET:
            xml_data_id = request.GET['id']
            xml_data = XMLdata.get(xml_data_id)
            template = Template.objects().get(pk=ObjectId(xml_data['schema']))
            context = RequestContext(request, {
                'edit': True,
                'template_name': template.title
            })
            curate_edit_data(request)
        elif 'template' in request.GET:
            context = RequestContext(
                request, {'template_name': request.GET['template']})
            curate_from_schema(request)
        elif 'templateid' in request.GET:
            pass

        template = loader.get_template('curate/curate_enter_data.html')

        return HttpResponse(template.render(context))
    except MDCSError, e:
        template = loader.get_template('curate/errors.html')
        context = RequestContext(request, {
            'errors': e.message,
        })
        return HttpResponse(template.render(context))
Esempio n. 7
0
def explore_detail_result_process(request):
    result_id = request.GET['id']
    xmlString = XMLdata.get(result_id)
    schemaId = xmlString['schema']
    if 'title' in request.GET:
        title = request.GET['title']
    else:
        title = xmlString['title']
    xmlString = xmltodict.unparse(xmlString['content']).encode('utf-8')
    xsltPath = os.path.join(settings.SITE_ROOT, 'static', 'resources', 'xsl',
                            'xml2html.xsl')
    xslt = etree.parse(xsltPath)
    transform = etree.XSLT(xslt)

    #Check if a custom detailed result XSLT has to be used
    try:
        if (xmlString != ""):
            dom = etree.fromstring(str(xmlString))
            schema = Template.objects.get(pk=schemaId)
            if schema.ResultXsltDetailed:
                shortXslt = etree.parse(
                    BytesIO(schema.ResultXsltDetailed.content.encode('utf-8')))
                shortTransform = etree.XSLT(shortXslt)
                newdom = shortTransform(dom)
            else:
                newdom = transform(dom)
    except Exception, e:
        #We use the default one
        newdom = transform(dom)
Esempio n. 8
0
def explore_detail_result_process(request) :
    result_id = request.GET['id']
    xmlString = XMLdata.get(result_id)
    schemaId = xmlString['schema']
    if 'title' in request.GET:
        title = request.GET['title']
    else:
        title = xmlString['title']
    xmlString = xmltodict.unparse(xmlString['content']).encode('utf-8')
    xsltPath = os.path.join(settings.SITE_ROOT, 'static', 'resources', 'xsl', 'xml2html.xsl')
    xslt = etree.parse(xsltPath)
    transform = etree.XSLT(xslt)

    #Check if a custom detailed result XSLT has to be used
    try:
        if (xmlString != ""):
            dom = etree.fromstring(str(xmlString))
            schema = Template.objects.get(pk=schemaId)
            if schema.ResultXsltDetailed:
                shortXslt = etree.parse(BytesIO(schema.ResultXsltDetailed.content.encode('utf-8')))
                shortTransform = etree.XSLT(shortXslt)
                newdom = shortTransform(dom)
            else:
                newdom = transform(dom)
    except Exception, e:
        #We use the default one
        newdom = transform(dom)
Esempio n. 9
0
def curate_edit_data(request):
    try:
        xml_data_id = request.GET['id']
        xml_data = XMLdata.get(xml_data_id)
        xml_content = xml_data['xml_file']
        request.session['curate_edit'] = True
        request.session['currentTemplateID'] = xml_data['schema']
        # remove previously created forms when editing a new one
        previous_forms = FormData.objects(user=str(request.user.id),
                                          xml_data_id__exists=True)

        for previous_form in previous_forms:
            if previous_form.schema_element_root is not None:
                delete_branch_from_db(previous_form.schema_element_root.pk)
            previous_form.delete()

        form_data = FormData(user=str(request.user.id),
                             template=xml_data['schema'],
                             name=xml_data['title'],
                             xml_data=xml_content,
                             xml_data_id=xml_data_id)
        form_data.save()

        request.session['curateFormData'] = str(form_data.pk)

        if 'form_id' in request.session:
            del request.session['form_id']
        if 'xmlDocTree' in request.session:
            del request.session['xmlDocTree']
    except:
        raise MDCSError("The document you are looking for doesn't exist.")
Esempio n. 10
0
def curate_enter_data(request):
    print "BEGIN curate_enter_data(request)"

    try:
        context = RequestContext(request, {})
        if 'id' in request.GET:
            xml_data_id = request.GET['id']
            xml_data = XMLdata.get(xml_data_id)
            template = Template.objects().get(pk=ObjectId(xml_data['schema']))
            context = RequestContext(request, {'edit': True, 'template_name': template.title})
            curate_edit_data(request)
        elif 'template' in request.GET:
            context = RequestContext(request, {'template_name': request.GET['template']})
            curate_from_schema(request)
        elif 'templateid' in request.GET:
            pass

        template = loader.get_template('curate/curate_enter_data.html')

        return HttpResponse(template.render(context))
    except MDCSError, e:
        template = loader.get_template('curate/errors.html')
        context = RequestContext(request, {
            'errors': e.message,
        })
        return HttpResponse(template.render(context))
def curate_edit_data(request):
    try:
        if 'useForm' in request.GET and request.GET['useForm'] == 'true':
            pass
        else:
            xml_data_id = request.GET['id']
            xml_data = XMLdata.get(xml_data_id)
            json_content = xml_data['content']
            xml_content = xmltodict.unparse(json_content)
            request.session['curate_edit_data'] = xml_content
            request.session['curate_edit'] = True
            request.session['currentTemplateID'] = xml_data['schema']
            # remove previously created forms when editing a new one
            previous_forms = FormData.objects(user=str(request.user.id), xml_data_id__exists=True)
            for previous_form in previous_forms:
                # TODO: check if need to delete all SchemaElements
                previous_form.delete()
            form_data = FormData(
                user=str(request.user.id),
                template=xml_data['schema'],
                name=xml_data['title'],
                xml_data=xml_content,
                xml_data_id=xml_data_id
            )
            form_data.save()
            request.session['curateFormData'] = str(form_data.id)

            if 'form_id' in request.session:
                del request.session['form_id']
            if 'formString' in request.session:
                del request.session['formString']
            if 'xmlDocTree' in request.session:
                del request.session['xmlDocTree']
    except:
        raise MDCSError("The document you are looking for doesn't exist.")
Esempio n. 12
0
def dashboard_detail_record(request,otherUser=None):
    template = None#loader.get_template('dashboard/my_dashboard_detail_record.html')
    record_id = request.GET['id']
    record_type = request.GET['type']
    user_id = None#request.POST.get('user_id','default value')
    if otherUser:
        user_id = otherUser#request.GET['user_id']
        template = loader.get_template('dashboard/my_dashboard_detail_recordotherusers.html')
    else:
        template = loader.get_template('dashboard/my_dashboard_detail_record.html')

    if record_type == 'form':
        form_data = FormData.objects.get(pk=ObjectId(record_id))
        xml_string = form_data.xml_data.encode(encoding='UTF-8')
        title = form_data.name
        schema_id = form_data.template
    elif record_type == 'record':
        xml_string = XMLdata.get(record_id)
        title = xml_string['title']
        schema_id = xml_string['schema']
        xml_string = XMLdata.unparse(xml_string['content']).encode('utf-8')
    else:
        raise Exception("Unknow record type: " + str(record_type))

    xslt_path = os.path.join(settings.SITE_ROOT, 'static', 'resources', 'xsl', 'xml2html.xsl')
    xslt = etree.parse(xslt_path)
    transform = etree.XSLT(xslt)

    dom = ''

    # Check if a custom detailed result XSLT has to be used
    try:
        if xml_string != "":
            dom = etree.fromstring(xml_string)
            schema = Template.objects.get(pk=schema_id)

            if schema.ResultXsltDetailed:
                short_xslt = etree.parse(BytesIO(schema.ResultXsltDetailed.content.encode('utf-8')))
                short_transform = etree.XSLT(short_xslt)
                newdom = short_transform(dom)
            else:
                newdom = transform(dom)
        else:
            newdom = 'No data has been saved to this form yet.'
    except Exception as e:
        # We use the default one
        newdom = transform(dom)

    result = str(newdom)

    context = RequestContext(request, {
        'XMLHolder': result,
        'title': title,
        'type': record_type,
    })
    if otherUser:
        context["user_id"] = otherUser

    return HttpResponse(template.render(context))
Esempio n. 13
0
def explore_detail_result_process(request, result_id):
    # result_id = request.GET['id']
    xmlString = XMLdata.get(result_id)
    if 'title' in request.GET:
        title = request.GET['title']
    else:
        title = None
    return get_detail_result(request, xmlString, title)
Esempio n. 14
0
def explore_detail_result_process(request):
    result_id = request.GET['id']
    xml_data = XMLdata.get(result_id)
    schema_id = xml_data['schema']
    if 'title' in request.GET:
        xml_data['title'] = request.GET['title']

    schema = Template.objects.get(pk=schema_id)
    return _create_context_detail_view(request, xml_data, schema)
Esempio n. 15
0
 def test_update_publish_draft(self):
     status = Status.ACTIVE
     new_xml = "<Resource localid='' status='"+status+"'><identity>" \
            "<title>My new software</title></identity><curation><publisher>PF</publisher><contact><name></name>" \
            "</contact></curation><content><description>This is a new record</description><subject></subject>" \
            "<referenceURL></referenceURL></content></Resource>"
     id = self.createXMLData(ispublished=True)
     xmlData = XMLdata.get(id)
     self.assertNotEquals(new_xml, XMLdata.unparse(xmlData['content']))
     adminId = self.getAdmin().id
     template = self.createTemplate()
     elements = SchemaElement.objects().all()
     self.assertEqual(len(elements), 0)
     elementsForm = FormData.objects().all()
     self.assertEqual(len(elementsForm), 0)
     formData = self.createFormData(user=adminId,
                                    name='name',
                                    template=str(template.id),
                                    xml_data=new_xml,
                                    xml_data_id=str(id))
     url = '/dashboard/update_publish_draft'
     data = {'draft_id': str(formData.id)}
     r = self.doRequestGetAdminClientLogged(url=url, data=data)
     xmlDataInDatabase = XMLdata.get(id)
     elements = SchemaElement.objects().all()
     self.assertEqual(len(elements), 0)
     elementsForm = FormData.objects().all()
     self.assertEqual(len(elementsForm), 0)
     self.assertEquals(
         etree.XML(new_xml).text,
         etree.XML(str(XMLdata.unparse(xmlDataInDatabase['content']))).text)
     self.assertEquals(True, xmlDataInDatabase.get('ispublished'))
     self.assertEquals(str(adminId), xmlDataInDatabase.get('iduser'))
     self.assertNotEquals(xmlData.get('lastmodificationdate'),
                          xmlDataInDatabase.get('lastmodificationdate'))
     self.assertNotEquals(xmlData.get('publicationdate'),
                          xmlDataInDatabase.get('publicationdate'))
     self.assertEquals(status, xmlDataInDatabase.get('status'))
Esempio n. 16
0
def update_publish(request):
    XMLdata.update_publish(request.GET['result_id'])
    resource = XMLdata.get(request.GET['result_id'])

    # Send mail to the user and the admin
    context = {'URI': MDCS_URI,
               'title': resource['title'],
               'publicationdate': resource['publicationdate'],
               'user': request.user.username}

    send_mail_to_managers(subject='Resource Published',
                                pathToTemplate='dashboard/email/resource_published.html',
                                context=context)
    return HttpResponse(json.dumps({}), content_type='application/javascript')
Esempio n. 17
0
def explore_detail_result_keyword(request):
    # template = loader.get_template('explore/explore_detail_results_keyword.html')
    template = loader.get_template('explore/test_f.html')
    # fhk_add_test1
    #xml to json
    data = tojson(request)
    #check response data
    result = data.content
    i = '\"@xmlns:xsi\": \"http://www.w3.org/2001/XMLSchema-instance\", '
    result = result.replace(i, '')
    u = '127.0.0.1'
    result = result.replace(u, '0.0.0.0')
    title = XMLdata.get(request.GET['id'])['title']
    context = RequestContext(request, {'XMLHolder': result, 'title': title})
    return HttpResponse(template.render(context))
Esempio n. 18
0
def __load_link_view(request):
    # retrieve document id
    # retrieve the projection content
    ref_node_id = request.POST["ref_node_id"]
    reference_node = get_navigation_node_for_document(ref_node_id,
                                                      request.POST["doc_id"])

    xml_document = XMLdata.get(request.POST["doc_id"])

    if "projection_view" in reference_node.options and reference_node.options[
            "projection_view"] is not None:
        projection_views = json.loads(
            reference_node.options["projection_view"])

        view_data = {
            "header": xml_document.get("title"),
            "type": "leaf",
            "views": []
        }

        # Send the annotation to the processor and collect the data
        for projection_view in projection_views:
            result_data = {"title": projection_view["title"], "data": None}

            # FIXME better handling of x-queries
            if "query" in projection_view.keys():
                result_data["data"] = process_cross_query(
                    request.POST["nav_id"], request.POST["doc_id"],
                    projection_view["query"], projection_view["data"])
            else:
                result_data["data"] = processview(request.POST["nav_id"],
                                                  request.POST["doc_id"],
                                                  projection_view["data"])

            view_data["views"].append(result_data)

        html_data = render(request, "explore_tree/components/view.html",
                           view_data)
        doc_id = str(reference_node.pk) + "." + str(xml_document["_id"])

        # return render(request, "explore_tree/components/view.html", view_data)
        return HttpResponse(json.dumps({
            "html": html_data.content,
            "doc_id": doc_id
        }),
                            status=HTTP_200_OK)
    else:
        return HttpResponse(json.dumps({}), HTTP_200_OK)
Esempio n. 19
0
def update_publish(request):
    XMLdata.update_publish(request.GET['result_id'])
    resource = XMLdata.get(request.GET['result_id'])

    # Send mail to the user and the admin
    context = {
        'URI': MDCS_URI,
        'title': resource['title'],
        'publicationdate': resource['publicationdate'],
        'user': request.user.username
    }

    send_mail_to_managers(
        subject='Resource Published',
        pathToTemplate='dashboard/email/resource_published.html',
        context=context)
    return HttpResponse(json.dumps({}), content_type='application/javascript')
Esempio n. 20
0
def __load_leaf_view(request):
    """ Load view for a leaf

    Parameters:
        -   request:

    Returns:
    """
    # Retrieve the view annotation
    xml_document = XMLdata.get(request.POST["doc_id"])
    navigation_node = Navigation.objects.get(pk=request.POST["node_id"])

    # Display XML file if "projection_view" annotation is not configured
    if "projection_view" not in navigation_node.options:
        # TODO transform the XML into a data table
        return HttpResponse(json.dumps({}), HTTP_200_OK)

    projection_views = json.loads(navigation_node.options["projection_view"])

    view_data = {
        "header": xml_document.get("title"),
        "type": "leaf",
        "views": []
    }

    # Send the annotation to the processor and collect the data
    for projection_view in projection_views:
        result_data = {"title": projection_view["title"], "data": None}

        # FIXME better handling of x-
        if "query" in projection_view.keys():
            result_data["data"] = process_cross_query(request.POST["nav_id"],
                                                      request.POST["doc_id"],
                                                      projection_view["query"],
                                                      projection_view["data"])
        else:
            result_data["data"] = processview(request.POST["nav_id"],
                                              request.POST["doc_id"],
                                              projection_view["data"])

        view_data["views"].append(result_data)

    return render(request, "explore_tree/components/view.html", view_data)
def curate_edit_data(request):
    try:
        if 'useForm' in request.GET and request.GET['useForm'] == 'true':
            pass
        else:
            xml_data_id = request.GET['id']
            request.session['curate_edit'] = True
            # remove previously created forms when editing a new one
            previous_forms = FormData.objects(user=str(request.user.id),
                                              xml_data_id__exists=True,
                                              isNewVersionOfRecord=False)
            for previous_form in previous_forms:
                if previous_form.schema_element_root is not None:
                    delete_branch_from_db(previous_form.schema_element_root.pk)
                previous_form.delete()

            #Check if a form_data already exists for this record
            form_data = FormData.objects(xml_data_id=xml_data_id).all().first()
            if not form_data:
                xml_data = XMLdata.get(xml_data_id)
                json_content = xml_data['content']
                xml_content = XMLdata.unparse(json_content)
                form_data = FormData(user=str(request.user.id),
                                     template=xml_data['schema'],
                                     name=xml_data['title'],
                                     xml_data=xml_content,
                                     xml_data_id=xml_data_id,
                                     isNewVersionOfRecord=xml_data.get(
                                         'ispublished', False))
                form_data.save()

            request.session['currentTemplateID'] = form_data.template
            request.session['curate_edit_data'] = form_data.xml_data
            request.session['curateFormData'] = str(form_data.pk)

            if 'form_id' in request.session:
                del request.session['form_id']
            if 'xmlDocTree' in request.session:
                del request.session['xmlDocTree']
    except:
        raise MDCSError("The document you are looking for doesn't exist.")
Esempio n. 22
0
def dashboard_detail_resource(request):
    template = loader.get_template(
        'dashboard/my_dashboard_detail_resource.html')
    result_id = request.GET['id']
    type = request.GET['type']

    if type == 'form':
        form_data = FormData.objects.get(pk=ObjectId(result_id))
        xmlString = form_data.xml_data.encode('utf-8')
        title = form_data.name
        schemaId = form_data.template
    elif type == 'record':
        xmlString = XMLdata.get(result_id)
        title = xmlString['title']
        schemaId = xmlString['schema']
        xmlString = XMLdata.unparse(xmlString['content']).encode('utf-8')

    xsltPath = os.path.join(settings.SITE_ROOT, 'static', 'resources', 'xsl',
                            'xml2html.xsl')
    xslt = etree.parse(xsltPath)
    transform = etree.XSLT(xslt)

    #Check if a custom detailed result XSLT has to be used
    try:
        if (xmlString != ""):
            dom = etree.fromstring(str(xmlString))
            schema = Template.objects.get(pk=schemaId)
            if schema.ResultXsltDetailed:
                shortXslt = etree.parse(
                    BytesIO(schema.ResultXsltDetailed.content.encode('utf-8')))
                shortTransform = etree.XSLT(shortXslt)
                newdom = shortTransform(dom)
            else:
                newdom = transform(dom)
        else:
            newdom = "No data to display"
    except Exception, e:
        #We use the default one
        newdom = transform(dom)
Esempio n. 23
0
def dashboard_detail_resource(request) :
    template = loader.get_template('dashboard/my_dashboard_detail_resource.html')
    result_id = request.GET['id']
    type = request.GET['type']

    if type=='form':
        form_data = FormData.objects.get(pk=ObjectId(result_id))
        xmlString = form_data.xml_data
        title = form_data.name
        schemaId = form_data.template
    elif type=='record':
        xmlString = XMLdata.get(result_id)
        title = xmlString['title']
        schemaId = xmlString['schema']
        xmlString = xmltodict.unparse(xmlString['content']).encode('utf-8')


    xsltPath = os.path.join(settings.SITE_ROOT, 'static', 'resources', 'xsl', 'xml2html.xsl')
    xslt = etree.parse(xsltPath)
    transform = etree.XSLT(xslt)

    #Check if a custom detailed result XSLT has to be used
    try:
        if (xmlString != ""):
            dom = etree.fromstring(str(xmlString))
            schema = Template.objects.get(pk=schemaId)
            if schema.ResultXsltDetailed:
                shortXslt = etree.parse(BytesIO(schema.ResultXsltDetailed.content.encode('utf-8')))
                shortTransform = etree.XSLT(shortXslt)
                newdom = shortTransform(dom)
            else:
                newdom = transform(dom)
        else:
            newdom = "No data to display"
    except Exception, e:
        #We use the default one
        newdom = transform(dom)
Esempio n. 24
0
def curate_edit_data(request):
    try:
        xml_data_id = request.GET['id']
        xml_data = XMLdata.get(xml_data_id)
        json_content = xml_data['content']
        xml_content = xmltodict.unparse(json_content)
        request.session['curate_edit_data'] = xml_content
        request.session['curate_edit'] = True
        request.session['currentTemplateID'] = xml_data['schema']
        # remove previously created forms when editing a new one
        previous_forms = FormData.objects(user=str(request.user.id), xml_data_id__exists=True)
        for previous_form in previous_forms:
            # cascade delete references
            for form_element_id in previous_form.elements.values():
                try:
                    form_element = FormElement.objects().get(pk=form_element_id)
                    if form_element.xml_element is not None:
                        try:
                            xml_element = XMLElement.objects().get(pk=str(form_element.xml_element.id))
                            xml_element.delete()
                        except:
                            # raise an exception when element not found
                            pass
                    form_element.delete()
                except:
                    # raise an exception when element not found
                    pass
            previous_form.delete()
        form_data = FormData(user=str(request.user.id), template=xml_data['schema'], name=xml_data['title'], xml_data=xml_content, xml_data_id=xml_data_id).save()
        request.session['curateFormData'] = str(form_data.id)
        if 'formString' in request.session:
            del request.session['formString']
        if 'xmlDocTree' in request.session:
            del request.session['xmlDocTree']
    except:
        raise MDCSError("The document you are looking for doesn't exist.")
Esempio n. 25
0
def processview(navigation_root_id, document_id, json_content):
    """
    # Function Name: processview(document_id,json_content)
    # Inputs:        document_id - Document ID
    #                json_content - name/path combinations to query
    # Outputs:       Query results page
    # Exceptions:    None
    # Description:   Processes view name/path combination and outputs name/value stored in MongoDB based on document_id

    Parameters:
        navigation_root_id:
        document_id:
        json_content:

    Returns:

    """
    object1 = XMLdata.get(document_id)
    tempobject1 = object1

    pviewoutlist = []
    if object1 is None:
        # FIXME error case not working if data is arrayType
        for item in json_content:
            pviewdict = {"name": item["name"], "error": item["path"]}

            pviewoutlist.append(pviewdict)
    else:
        for item in json_content:
            if "type" in item and item["type"] == "array":
                pviewoutlist.append(
                    {"items": process_array_type(object1, item)})
            else:
                pathflag = True
                pviewname = item['name']
                path = item['path']
                pviewdict = {}
                pathstring = path.split('.')

                for pstringitem in pathstring:
                    tempobject1 = tempobject1.get(pstringitem)

                    if tempobject1 is None:
                        pathflag = False
                        pviewdict['name'] = pviewname
                        pviewdict['error'] = path
                        pviewoutlist.append(pviewdict)
                        break

                if pathflag:
                    pviewdict['name'] = pviewname
                    pviewdict['value'] = tempobject1

                    if "link" in item:
                        linked_node = get_navigation_node_by_name(
                            navigation_root_id, item["link"])

                        if linked_node is None:
                            pviewdict["link"] = "error"
                        else:
                            pviewdict["link"] = "%s %s" % (str(
                                linked_node.pk), document_id)

                    pviewoutlist.append(pviewdict)

                tempobject1 = object1

    return pviewoutlist
Esempio n. 26
0
def __load_link_view(request):
    """ Load link view for a link

    :param request:
    :return:
    """
    ref_node_id = request.POST["ref_node_id"]


    reference_node = get_navigation_node_for_document(ref_node_id, request.POST["doc_id"])

    navigation_name2 = request.POST["ref_node_id"]#
    xml_document = XMLdata.get(request.POST["doc_id"])#
    try :
        if "projection_view" in reference_node.options and reference_node.options["projection_view"] is not None:
            projection_views = json.loads(reference_node.options["projection_view"])

            view_data = {
                "header": xml_document.get("title"),
                "type": "leaf",
                "views": []
            }

            my_listof_ordereddicts_cross_docs2 =[]#
            query_and_results2 = []#
            my_listof_ordereddicts2 = []#
            resultat2 = []
            resultat3 = []
            my_list_of_cross_results = []
            # Send the annotation to the processor and collect the data
            for projection_view in projection_views:
                result_data = {
                    "title": projection_view["title"],
                    "data": None
                }

                # FIXME better handling of x-queries
                if "query" in projection_view.keys():
                    my_projections = []#
                    # Get the names of the brakets which need to be displayed
                    for value in projection_view["data"]:#
                        my_projections.append(value.get('path'))#
                    result_data["data"] = process_cross_query(request.POST["nav_id"], request.POST["doc_id"],
                                                              projection_view["query"], projection_view["data"])
                    # Set the documents which must be queried
                    doc_query_proc = {
                        "_id": ObjectId(request.POST["doc_id"])
                    }

                    quiered_docs = doc_to_query(1)

                    co_dict = {}

                    for id_doc in quiered_docs:
                        other_doc_query = {
                            "_id" : ObjectId(id_doc)
                        }

                        for projection in my_projections:

                            proj_co = {
                                my_projections[my_projections.index(projection)] : 1
                            }

                            res_co = XMLdata.executeQueryFullResult(other_doc_query,proj_co)

                            try:

                                doc_projco = get_projection(res_co[0])
                                s = str(my_projections[my_projections.index(projection)])
                                y = s.split(".")
                                attribute = y[len(y)-1]

                                result_cross = doc_projco
                                my_list_of_cross_results.append((attribute,result_cross))
                                global list_of_ordered_dict_cross_docs
                                list_of_ordered_dict_cross_docs = res_co
                                my_listof_ordereddicts_cross_docs2.append(res_co)
                                if "OrderedDict" in str(doc_projco):
                                    pass
                                else:
                                    querry_doc1 = query_and_results2[len(query_and_results2)-1]#.split(".")
                                    querry_doc = (querry_doc1.split("."))
                                    q_doc = querry_doc[len(querry_doc)-1]
                                    resultat3.append((q_doc,doc_projco))
                            except:
                                res_co = ''
                else:
                    my_projections = []
                    for value in projection_view["data"]:
                        my_projections.append(value.get('path'))
                    id_doc_to_query = {
                        "_id": ObjectId(request.POST["doc_id"])
                    }

                    for projection in my_projections:
                        proj_co = {
                            my_projections[my_projections.index(projection)] : 1
                        }

                        res_co = XMLdata.executeQueryFullResult(id_doc_to_query,proj_co)
                        query_and_results2.append(projection)
                        try:
                            doc_projco = get_projection(res_co[0])
                            global list_of_ordered_dict
                            list_of_ordered_dict = res_co
                            my_listof_ordereddicts2.append(res_co)
                            results_initial_doc.append(doc_projco)
                            if "OrderedDict" in str(doc_projco):
                                pass
                            else:

                                querry_doc1 = query_and_results2[len(query_and_results2)-1]#.split(".")
                                querry_doc = (querry_doc1.split("."))
                                q_doc = querry_doc[len(querry_doc)-1]
                                resultat2.append((q_doc,doc_projco))
                        except:
                            res_co = ''
                    result_data["data"] = processview(request.POST["nav_id"], request.POST["doc_id"],
                                                      projection_view["data"])
                    my_result_to_dwld.append(result_data["data"])

                view_data["views"].append(result_data)

            my_node = str(get_node_name(navigation_name2))+"_"+str(request.POST["doc_id"])
            query_and_results_tab.append(query_and_results2)
            my_listof_ordereddicts_cross_docs_tab.append(my_listof_ordereddicts_cross_docs2)
            navigation_name_tab.append(navigation_name2)
            my_listof_ordereddicts_tab.append(my_listof_ordereddicts2)
            resultat.append(resultat2)

            my_list_of_cross_results_f.append(my_list_of_cross_results)
            my_tab.append(my_node)

            html_data = render(request, "explore_tree/components/view.html", view_data)
            doc_id = str(reference_node.pk) + "." + str(xml_document["_id"])

            return HttpResponse(json.dumps({"html": html_data.content, "doc_id": doc_id}), status=HTTP_200_OK)
        else:
            return HttpResponse(json.dumps({}), HTTP_200_OK)
    except:
        #"NOT FOUND"
    #else:
        return HttpResponse(json.dumps({}), HTTP_200_OK)
Esempio n. 27
0
def load_leaf_view(request, docid):
    """ Load view for a leaf

    Parameters:
        -   request
        - doc id

    Returns:
    """

    navigation_name2=request.POST["node_id"]

    xml_document = XMLdata.get(docid)
    navigation_node = Navigation.objects.get(pk=request.POST["node_id"])

    # Display XML file if "projection_view" annotation is not configured
    if "projection_view" not in navigation_node.options:
        # TODO transform the XML into a data table
        return HttpResponse(json.dumps({}), HTTP_200_OK)

    projection_views = json.loads(navigation_node.options["projection_view"])

    view_data = {
        "header": xml_document.get("title"),
        "type": "leaf",
        "views": []
    }
    #Initialize parameters in order to download later some information
    my_listof_ordereddicts_cross_docs2 =[]
    query_and_results2 = []
    my_listof_ordereddicts2 = []
    resultat2 = []
    resultat3 = []
    my_list_of_cross_results = []
    # Send the annotation to the processor and collect the data
    for projection_view in projection_views:
        result_data = {
            "title": projection_view["title"],
            "data": None
        }

        # FIXME better handling of x-
        if "query" in projection_view.keys():

            my_projections = []
            # Get the names of the brakets which need to be displayed
            for value in projection_view["data"]:
                my_projections.append(value.get('path'))

            result_data["data"] = process_cross_query(request.POST["nav_id"], docid,
                                                      projection_view["query"], projection_view["data"])
            # Set the documents which must be queried
            doc_query_proc = {
                "_id": ObjectId(docid)
            }

            quiered_docs = doc_to_query(1)

            co_dict = {}

            for id_doc in quiered_docs:
                other_doc_query = {
                    "_id" : ObjectId(id_doc)
                }

                for projection in my_projections:

                    proj_co = {
                        my_projections[my_projections.index(projection)] : 1
                    }

                    res_co = XMLdata.executeQueryFullResult(other_doc_query,proj_co)

                    try:

                        doc_projco = get_projection(res_co[0])
                        s = str(my_projections[my_projections.index(projection)])
                        y = s.split(".")
                        attribute = y[len(y)-1]

                        result_cross = doc_projco
                        my_list_of_cross_results.append((attribute,result_cross))
                        global list_of_ordered_dict_cross_docs
                        list_of_ordered_dict_cross_docs = res_co
                        my_listof_ordereddicts_cross_docs2.append(res_co)
                        if "OrderedDict" in str(doc_projco):
                            pass
                        else:
                            querry_doc1 = query_and_results2[len(query_and_results2)-1]#.split(".")
                            querry_doc = (querry_doc1.split("."))
                            q_doc = querry_doc[len(querry_doc)-1]
                            resultat3.append((q_doc,doc_projco))
                    except:
                        res_co = ''

        else:
            my_projections = []
            for value in projection_view["data"]:
                my_projections.append(value.get('path'))
            id_doc_to_query = {
                "_id": ObjectId(docid)
            }

            for projection in my_projections:
                proj_co = {
                    my_projections[my_projections.index(projection)] : 1
                }

                res_co = XMLdata.executeQueryFullResult(id_doc_to_query,proj_co)
                query_and_results2.append(projection)
                try:
                    doc_projco = get_projection(res_co[0])
                    global list_of_ordered_dict
                    list_of_ordered_dict = res_co
                    my_listof_ordereddicts2.append(res_co)
                    results_initial_doc.append(doc_projco)

                    if "OrderedDict" in str(doc_projco):
                        pass
                    else:

                        querry_doc1 = query_and_results2[len(query_and_results2)-1]#.split(".")
                        querry_doc = (querry_doc1.split("."))
                        q_doc = querry_doc[len(querry_doc)-1]
                        resultat2.append((q_doc,doc_projco))
                except:
                    res_co = ''

            result_data["data"] = processview(request.POST["nav_id"], docid, projection_view["data"])
            my_result_to_dwld.append(result_data["data"])

        view_data["views"].append(result_data)
    my_node = str(get_node_name(navigation_name2))+"_"+str(request.POST["doc_id"])
    query_and_results_tab.append(query_and_results2)
    my_listof_ordereddicts_cross_docs_tab.append(my_listof_ordereddicts_cross_docs2)
    navigation_name_tab.append(navigation_name2)
    my_listof_ordereddicts_tab.append(my_listof_ordereddicts2)
    resultat.append(resultat2)

    my_list_of_cross_results_f.append(my_list_of_cross_results)
    my_tab.append(my_node)

    return view_data