Ejemplo n.º 1
0
def reload_form(request):
    """
    Reload the form string from latest version saved
    :param request:
    :return:
    """
    try:
        form_data_id = request.session['curateFormData']
        form_data = FormData.objects().get(pk=form_data_id)
        xml_data = form_data.xml_data

        template_id = request.session['currentTemplateID']
        template_object = Template.objects.get(pk=template_id)
        xsd_doc_data = template_object.content

        # the form has been saved already
        if xml_data is not None and xml_data != '':
            request.session['curate_edit'] = True
            root_element_id = generate_form(request, xsd_doc_data, xml_data, config=load_config())
        # the form has never been saved
        else:
            root_element_id = generate_form(request, xsd_doc_data, config=load_config())

        root_element = SchemaElement.objects.get(pk=root_element_id)
        renderer = ListRenderer(root_element, request)
        html_form = renderer.render()
        request.session['form_id'] = str(root_element_id)
        return HttpResponse(json.dumps({'xsdForm': html_form}), content_type='application/javascript')
    except Exception, e:
        return HttpResponse({}, status=400)
Ejemplo n.º 2
0
def reload_form(request):
    """
    Reload the form string from latest version saved
    :param request:
    :return:
    """
    try:
        form_data_id = request.session['curateFormData']
        form_data = FormData.objects().get(pk=form_data_id)
        xml_data = form_data.xml_data

        template_id = request.session['currentTemplateID']
        template_object = Template.objects.get(pk=template_id)
        xsd_doc_data = template_object.content

        # the form has been saved already
        if xml_data is not None and xml_data != '':
            request.session['curate_edit'] = True
            root_element_id = generate_form(request, xsd_doc_data, xml_data, config=load_config())
        # the form has never been saved
        else:
            root_element_id = generate_form(request, xsd_doc_data, config=load_config())

        root_element = SchemaElement.objects.get(pk=root_element_id)
        renderer = ListRenderer(root_element, request)
        html_form = renderer.render()
        request.session['form_id'] = str(root_element_id)
        return HttpResponse(json.dumps({'xsdForm': html_form}), content_type='application/javascript')
    except Exception, e:
        return HttpResponse({}, status=400)
Ejemplo n.º 3
0
    def test_list_renderer(self):
        main_directory = self.schema_data_handler.dirname
        main_dir_len = len(main_directory) + 1

        filepath_list = []

        for root, dirs, files in walk(main_directory):
            for filename in files:
                file_ext = splitext(filename)

                if file_ext[1] == '.xsd':
                    full_path = join(root, file_ext[0])
                    filepath_list.append(full_path[main_dir_len:])

        report_content = []
        error_count = 0

        for filepath in filepath_list:
            report_line = filepath

            try:
                xsd_data = self.schema_data_handler.get_xsd2(filepath)
                self.request.session['xmlDocTree'] = etree.tostring(xsd_data)

                root_pk = generate_form(self.request)
                root_element = SchemaElement.objects.get(pk=root_pk)

                renderer = ListRenderer(root_element)
                renderer.render()

                if len(renderer.warnings) != 0:
                    report_line += ',NOK,' + ','.join(renderer.warnings) + '\n'
                    error_count += 1
                else:  # No warnings yielded by the renderer
                    report_line += ',OK\n'
            except Exception as e:
                report_line += ',NOK,' + e.message + '\n'
                error_count += 1

            report_content.append(report_line)

        with open(join(SITE_ROOT, 'full_tests_report.csv'),
                  'w') as report_file:
            report_file.writelines(report_content)

        self.assertEqual(error_count, 0)
    def test_list_renderer(self):
        main_directory = self.schema_data_handler.dirname
        main_dir_len = len(main_directory) + 1

        filepath_list = []

        for root, dirs, files in walk(main_directory):
            for filename in files:
                file_ext = splitext(filename)

                if file_ext[1] == '.xsd':
                    full_path = join(root, file_ext[0])
                    filepath_list.append(full_path[main_dir_len:])

        report_content = []
        error_count = 0

        for filepath in filepath_list:
            report_line = filepath

            try:
                xsd_data = self.schema_data_handler.get_xsd2(filepath)
                self.request.session['xmlDocTree'] = etree.tostring(xsd_data)

                root_pk = generate_form(self.request)
                root_element = SchemaElement.objects.get(pk=root_pk)

                renderer = ListRenderer(root_element)
                renderer.render()

                if len(renderer.warnings) != 0:
                    report_line += ',NOK,' + ','.join(renderer.warnings) + '\n'
                    error_count += 1
                else:  # No warnings yielded by the renderer
                    report_line += ',OK\n'
            except Exception as e:
                report_line += ',NOK,' + e.message + '\n'
                error_count += 1

            report_content.append(report_line)

        with open(join(SITE_ROOT, 'full_tests_report.csv'), 'w') as report_file:
            report_file.writelines(report_content)

        self.assertEqual(error_count, 0)
Ejemplo n.º 5
0
def generate_xsd_form(request):
    """ Renders HTMl form for display.

    Parameters:
        request:

    Returns:
        str: HTML form
    """
    try:
        if 'form_id' in request.session:
            root_element_id = request.session['form_id']
            form_data = None
            request.session['curate_edit'] = False
        else:  # If this is a new form, generate it and store the root ID
            # get the xsd tree when going back and forth with review step
            if 'xmlDocTree' in request.session:
                xsd_doc_data = request.session['xmlDocTree']
            else:
                template_id = request.session['currentTemplateID']
                template_object = Template.objects.get(pk=template_id)
                xsd_doc_data = template_object.content

            # get form data from the database (empty one or existing one)
            form_data_id = request.session['curateFormData']
            form_data = FormData.objects.get(pk=ObjectId(form_data_id))

            if form_data.xml_data is not None:
                xml_doc_data = form_data.xml_data
            else:
                xml_doc_data = None

            root_element_id = generate_form(request, xsd_doc_data, xml_doc_data, config=load_config())
            request.session['form_id'] = str(root_element_id)

        root_element = SchemaElement.objects.get(pk=root_element_id)

        if form_data is not None:
            if form_data.schema_element_root is not None:
                delete_branch_from_db(form_data.schema_element_root.pk)

            form_data.update(set__schema_element_root=root_element)
            form_data.reload()

        renderer = ListRenderer(root_element, request)
        html_form = renderer.render()
    except Exception as e:
        renderer = DefaultRenderer(SchemaElement(), {})

        if e.message is not None:
            err_message = e.message
        else:
            err_message = "An unknown error raised " + e.__class__.__name__

        html_form = renderer._render_form_error(err_message)

    return HttpResponse(json.dumps({'xsdForm': html_form}), content_type='application/javascript')
Ejemplo n.º 6
0
def remove_element(request):
    element_id = request.POST['id']
    # sub_element = SchemaElement.objects.get(pk=element_id)
    element_list = SchemaElement.objects(children=element_id)

    if len(element_list) == 0:
        raise ValueError("No SchemaElement found")
    elif len(element_list) > 1:
        raise ValueError("More than one SchemaElement found")

    # Removing the element from the data structure
    schema_element = element_list[0]
    schema_element_to_pull = SchemaElement.objects.get(pk=element_id)
    schema_element.update(pull__children=schema_element_to_pull)

    schema_element.reload()
    update_branch_xpath(schema_element)

    # Deleting the branch from the database
    delete_branch_from_db(element_id)

    children_number = len(schema_element.children)

    # TODO Move it to parser function
    # FIXME Sequence elem it might not work
    if len(schema_element.children) == 0:
        elem_iter = SchemaElement()

        if schema_element.tag == 'element':
            elem_iter.tag = 'elem-iter'
        elif schema_element.tag == 'choice':
            elem_iter.tag = 'choice-iter'
        elif schema_element.tag == 'sequence':
            elem_iter.tag = 'sequence-iter'

        elem_iter.save()
        schema_element.update(add_to_set__children=[elem_iter])
        schema_element.reload()

    response = {
        'code': 0,
        'html': ""
    }

    if children_number > schema_element.options['min']:
        return HttpResponse(json.dumps(response), status=HTTP_200_OK)
    else:  # len(schema_element.children) == schema_element.options['min']
        if schema_element.options['min'] != 0:
            response['code'] = 1
        else:  # schema_element.options['min'] == 0
            renderer = ListRenderer(schema_element, request)
            html_form = renderer.render(True)

            response['code'] = 2
            response['html'] = html_form

        return HttpResponse(json.dumps(response))
Ejemplo n.º 7
0
def generate_xsd_form(request):
    """ Renders HTMl form for display.

    Parameters:
        request:

    Returns:
        str: HTML form
    """
    try:
        if 'form_id' in request.session:
            root_element_id = request.session['form_id']
            form_data = None
            request.session['curate_edit'] = False
        else:  # If this is a new form, generate it and store the root ID
            # get the xsd tree when going back and forth with review step
            if 'xmlDocTree' in request.session:
                xsd_doc_data = request.session['xmlDocTree']
            else:
                template_id = request.session['currentTemplateID']
                template_object = Template.objects.get(pk=template_id)
                xsd_doc_data = template_object.content

            # get form data from the database (empty one or existing one)
            form_data_id = request.session['curateFormData']
            form_data = FormData.objects.get(pk=ObjectId(form_data_id))

            if form_data.xml_data is not None:
                xml_doc_data = form_data.xml_data
            else:
                xml_doc_data = None

            root_element_id = generate_form(request, xsd_doc_data, xml_doc_data, config=load_config())
            request.session['form_id'] = str(root_element_id)

        root_element = SchemaElement.objects.get(pk=root_element_id)

        if form_data is not None:
            if form_data.schema_element_root is not None:
                delete_branch_from_db(form_data.schema_element_root.pk)

            form_data.update(set__schema_element_root=root_element)
            form_data.reload()

        renderer = ListRenderer(root_element, request)
        html_form = renderer.render()
    except Exception as e:
        renderer = DefaultRenderer(SchemaElement(), {})

        if e.message is not None:
            err_message = e.message
        else:
            err_message = "An unknown error raised " + e.__class__.__name__

        html_form = renderer._render_form_error(err_message)

    return HttpResponse(json.dumps({'xsdForm': html_form}), content_type='application/javascript')
Ejemplo n.º 8
0
def remove_element(request):
    element_id = request.POST['id']
    # sub_element = SchemaElement.objects.get(pk=element_id)
    element_list = SchemaElement.objects(children=element_id)

    if len(element_list) == 0:
        raise ValueError("No SchemaElement found")
    elif len(element_list) > 1:
        raise ValueError("More than one SchemaElement found")

    # Removing the element from the data structure
    schema_element = element_list[0]
    schema_element.update(pull__children=element_id)

    schema_element.reload()
    update_branch_xpath(schema_element)

    # Deleting the branch from the database
    delete_branch_from_db(element_id)

    children_number = len(schema_element.children)

    # TODO Move it to parser function
    # FIXME Sequence elem it might not work
    if len(schema_element.children) == 0:
        elem_iter = SchemaElement()

        if schema_element.tag == 'element':
            elem_iter.tag = 'elem-iter'
        elif schema_element.tag == 'choice':
            elem_iter.tag = 'choice-iter'
        elif schema_element.tag == 'sequence':
            elem_iter.tag = 'sequence-iter'

        elem_iter.save()
        schema_element.update(add_to_set__children=[elem_iter])
        schema_element.reload()

    response = {
        'code': 0,
        'html': ""
    }

    if children_number > schema_element.options['min']:
        return HttpResponse(json.dumps(response), status=HTTP_200_OK)
    else:  # len(schema_element.children) == schema_element.options['min']
        if schema_element.options['min'] != 0:
            response['code'] = 1
        else:  # schema_element.options['min'] == 0
            renderer = ListRenderer(schema_element, request)
            html_form = renderer.render(True)

            response['code'] = 2
            response['html'] = html_form

        return HttpResponse(json.dumps(response))
Ejemplo n.º 9
0
def retrieve_rendered_form(request):
    """Retrieve a form

    :param request:
    :return:
    """
    root_pk = generate_form(request)
    root_element = SchemaElement.objects.get(pk=root_pk)

    renderer = ListRenderer(root_element)
    return renderer.render()
Ejemplo n.º 10
0
def retrieve_rendered_form(request):
    """Retrieve a form

    :param request:
    :return:
    """
    root_pk = generate_form(request)
    root_element = SchemaElement.objects.get(pk=root_pk)

    renderer = ListRenderer(root_element)
    return renderer.render()
Ejemplo n.º 11
0
def generate_xsd_form(request):
    """ Renders HTMl form for display.

    Parameters:
        request:

    Returns:
        str: HTML form
    """
    try:
        if 'form_id' in request.session:
            root_element_id = request.session['form_id']
            form_data = None
            request.session['curate_edit'] = False
        else:  # If this is a new form, generate it and store the root ID
            # get the xsd tree when going back and forth with review step
            if 'xmlDocTree' in request.session:
                xsd_doc_data = request.session['xmlDocTree']
            else:
                template_id = request.session['currentTemplateID']
                template_object = Template.objects.get(pk=template_id)
                xsd_doc_data = template_object.content

            # get form data from the database (empty one or existing one)
            form_data_id = request.session['curateFormData']
            form_data = FormData.objects.get(pk=ObjectId(form_data_id))

            if form_data.xml_data is not None:
                xml_doc_data = form_data.xml_data
            else:
                xml_doc_data = None

            root_element_id = generate_form(request,
                                            xsd_doc_data,
                                            xml_doc_data,
                                            config=load_config())
            request.session['form_id'] = str(root_element_id)

        root_element = SchemaElement.objects.get(pk=root_element_id)

        ##### xxxxxxxxxxxxxxx
        text2choice(root_element)

        if form_data is not None:
            if form_data.schema_element_root is not None:
                delete_branch_from_db(form_data.schema_element_root.pk)

            form_data.update(set__schema_element_root=root_element)
            form_data.reload()

        renderer = ListRenderer(root_element, request)
        html_form = renderer.render()
    except Exception as e:
        renderer = DefaultRenderer(SchemaElement(), {})

        if e.message is not None:
            err_message = e.message
        else:
            err_message = "An unknown error raised " + e.__class__.__name__

        html_form = renderer._render_form_error(err_message)

    #### add image upload button
    try:
        page = etree.fromstring(html_form)
        hrefs = page.xpath(u"//li")
        for href in hrefs:
            if href.text.strip() == "imageID":
                form = etree.SubElement(
                    href,
                    'form',
                    attrib={
                        'action':
                        '''javascript:var request = $.ajax({url: "/rest/blob?id=1243",
          method: "POST",
          data: new FormData(document.getElementById('blob321')),
        processData: false,
        contentType: false
        }).done(function(res){document.getElementById('%s').value=res.handle;}).fail(function(res){});'''
                        % (href.getchildren()[0].attrib['id']),
                        'method':
                        'post',
                        'id':
                        'blob321',
                        'enctype':
                        'multipart/form-data'
                    })

                attributes = href.getchildren()[0].attrib
                attributes['type'] = 'submit'
                attributes['value'] = 'upload'
                etree.SubElement(form,
                                 'input',
                                 attrib={
                                     'id': 'blob123',
                                     'type': 'file',
                                     'name': 'blob'
                                 })
                form.append(href.getchildren()[0])

        html_form = etree.tostring(page)
    except Exception as e:
        pass

    return HttpResponse(json.dumps({'xsdForm': html_form}),
                        content_type='application/javascript')