FederationForm   A
last analyzed

Size/Duplication

Total Lines 16
Duplicated Lines 100 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 16
loc 16
rs 10

1 Method

Rating   Name   Duplication   Size   Complexity  
A __init__() 9 9 1

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
#################################################################
2
# MET v2 Metadate Explorer Tool
3
#
4
# This Software is Open Source. See License: https://github.com/TERENA/met/blob/master/LICENSE.md
5
# Copyright (c) 2012, TERENA All rights reserved.
6
#
7
# This Software is based on MET v1 developed for TERENA by Yaco Sistemas, http://www.yaco.es/
8
# MET v2 was developed for TERENA by Tamim Ziai, DAASI International GmbH, http://www.daasi.de
9
# Current version of MET has been revised for performance improvements by Andrea Biancini,
10
# Consortium GARR, http://www.garr.it
11
##########################################################################
12
13
from django import forms
14
from django.utils.translation import ugettext_lazy as _
15
from django.forms.widgets import CheckboxSelectMultiple, Widget
16
from django.forms.extras.widgets import SelectDateWidget
17
from django.forms.utils import ErrorDict, flatatt
18
19
from django.utils import timezone
20
from dateutil.relativedelta import relativedelta
21
22
from django.utils.html import format_html
23
from django.utils.safestring import mark_safe
24
from met.metadataparser.models import Federation, Entity, EntityType, EntityCategory
25
26
27
class MultiURLforMetadata(Widget):
28
    def render(self, name, value, attrs=None):
29
        if value is None:
30
            value = ""
31
32
        final_attrs = self.build_attrs(attrs, name=name)
33
        output = []
34
        output.append(format_html(
35
            '<table id="metadata_type" class="display" cellspacing="0" width="100%"><thead><tr><th>Metadata</th><th>Type</th></tr></thead><tbody>', flatatt(final_attrs)))
36
37
        for curpair in value.split("|"):
38
            val = ''.join(curpair)
39
            val = curpair.split(";")
40
41
            if len(val) == 1:
42
                val.append("All")
43
44
            if val[0]:
45
                output.append('<tr><td>%s</th><td>%s</td></tr>' %
46
                              (val[0], val[1] or 'All'))
47
48
        output.append('''
49
            </tbody></table>
50
            <br/>
51
52
            <button id="delete" type="button">Delete selected URL</button>
53
            <br/><br/><br/>
54
55
            <fieldset class="control-group" id="new_URL_set">
56
            Meta URL: <input type="url" name="meta_URL" id="meta_URL" />
57
            <select name="type_URL" id="type_URL"><option value="All">All</option><option value="IDP">IDP</option><option value="SP">SP</option></select>
58
            <input id="add" type="button" value="Add URL" />
59
            </fieldset>
60
        ''')
61
62
        output.append(
63
            '<input type="hidden" id="id_%s" name="%s" value=""><br/><br/>' % (name, name))
64
65
        output.append('''<script>
66
            $(document).ready(function() {
67
                $.extend( $.fn.dataTable.defaults, {
68
                    "searching": false,
69
                    "ordering":  false,
70
                    "paging":    false,
71
                    "info":      false
72
                }); 
73
   
74
                var table = $('#metadata_type').DataTable();
75
                $('#metadata_type tbody').on( 'click', 'tr', function () {
76
                    $(this).toggleClass('selected');
77
                });
78
                var text = "";
79
                table.rows().every( function () {
80
                    var data = this.data();
81
                    text += data[0] +  ";" + data[1] + "|";
82
                } );
83
                text = text.substring(0, text.length - 1);
84
                $('#id_%s').val(text);
85
86
                $('#add').click( function () {
87
                    if ($('#meta_URL').val() == undefined) return;
88
                    texturl = $('#meta_URL').val();
89
                    var urlpattern = new RegExp('([a-zA-Z\d]+:\\/\\/)?((\\w+:\\w+@)?([a-zA-Z\\d.-]+\\.[A-Za-z]{2,4})(:\\d+)?(\\/.*)?)','i'); // fragment locater
90
                    if (!urlpattern.test($('#meta_URL').val())) {
91
                        $('#new_URL_set').addClass("error");
92
                        return; 
93
                    }
94
95
                    $('#new_URL_set').removeClass("error");
96
                    table.row.add([$('#meta_URL').val(), $('#type_URL').val()]).draw();
97
                    $('#meta_URL').val("");
98
                    $('#type_URL').val("All");
99
100
                    var text = "";
101
                    table.rows().every( function () {
102
                        var data = this.data();
103
                        text +=data[0] +  ";" + data[1] + "|";
104
                    } );
105
                    text = text.substring(0, text.length - 1);
106
                    $('#id_%s').val(text);
107
                });
108
109
                $('#delete').click( function () {
110
                    table.row('.selected').remove().draw(false);
111
                   
112
                    var text = "";
113
                    table.rows().every( function () {
114
                        var data = this.data();
115
                        text +=data[0] +  ";" + data[1] + "|";
116
                    } );
117
                    text = text.substring(0, text.length - 1);
118
                    $('#id_%s').val(text); 
119
                });
120
            });
121
            </script>''' % (name, name, name))
122
123
        return mark_safe('\n'.join(output))
124
125
126 View Code Duplication
class FederationForm(forms.ModelForm):
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
127
128
    def __init__(self, *args, **kwargs):
129
        super(FederationForm, self).__init__(*args, **kwargs)
130
        editor_users_choices = self.fields['editor_users'].widget.choices
131
        self.fields['editor_users'].widget = CheckboxSelectMultiple(
132
            choices=editor_users_choices)
133
        self.fields['editor_users'].help_text = _("This/these user(s) can edit this "
134
                                                  "federation and its entities")
135
136
        self.fields['file_url'].widget = MultiURLforMetadata()
137
138
    class Meta(object):
139
        model = Federation
140
        fields = ['name', 'url', 'registration_authority', 'country', 'logo',
141
                  'is_interfederation', 'type', 'fee_schedule_url', 'file_url', 'file', 'editor_users']
142
143
144 View Code Duplication
class EntityForm(forms.ModelForm):
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
145
146
    def __init__(self, *args, **kwargs):
147
        super(EntityForm, self).__init__(*args, **kwargs)
148
        editor_users_choices = self.fields['editor_users'].widget.choices
149
        self.fields['editor_users'].widget = CheckboxSelectMultiple(
150
            choices=editor_users_choices)
151
        self.fields['editor_users'].help_text = _("These users can edit only "
152
                                                  "this entity")
153
154
    class Meta(object):
155
        model = Entity
156
        fields = ['registration_authority', 'file_url', 'file', 'editor_users']
157
158
159
class ChartForm(forms.Form):
160
    fromDate = forms.DateField(label=_(u'Start date'),
161
                               help_text=_(u"Statistics start date."), initial=timezone.now() - relativedelta(days=11),
162
                               widget=SelectDateWidget(years=range(timezone.datetime.today().year, 2012, -1)))
163
164
    toDate = forms.DateField(label=_(u'End date'),
165
                             help_text=_(u"Statistics end date."), initial=timezone.now() - relativedelta(days=1),
166
                             widget=SelectDateWidget(years=range(timezone.datetime.today().year, 2012, -1)))
167
168
    def is_valid(self):
169
        result = super(ChartForm, self).is_valid()
170
171
        if result:
172
            result = self.cleaned_data['fromDate'] <= self.cleaned_data['toDate']
173
            if not result:
174
                errors = ErrorDict()
175
                errors['toDate'] = 'End date must not be before Start date'
176
                self._errors = errors
177
            else:
178
                result = (self.cleaned_data['toDate'] -
179
                          self.cleaned_data['fromDate']).days < 12
180
                if not result:
181
                    errors = ErrorDict()
182
                    errors['fromDate'] = 'The maximum number of days shown in the chart is 11 days'
183
                    self._errors = errors
184
185
        return result
186
187
    def __init__(self, *args, **kwargs):
188
        self.instance = kwargs.pop('instance')
189
        super(ChartForm, self).__init__(*args, **kwargs)
190
191
    class Meta(object):
192
        exclude = []
193
194
195
class EntityCommentForm(forms.Form):
196
    email = forms.EmailField(label=_(u'Your email address'),
197
                             help_text=_(u"Please enter your email address here."))
198
199
    comment = forms.CharField(max_length=1000, label=_(u"Your comment"),
200
                              help_text=_(u"Please enter your comment here."),
201
                              widget=forms.Textarea(attrs={'cols': '100', 'rows': '10'}))
202
203
    def __init__(self, *args, **kwargs):
204
        self.instance = kwargs.pop('instance')
205
        super(EntityCommentForm, self).__init__(*args, **kwargs)
206
207
    class Meta(object):
208
        exclude = []
209
210
211
class EntityProposalForm(forms.Form):
212
    email = forms.EmailField(label=_(u'Your email address'),
213
                             help_text=_(u"Please enter your email address here."))
214
215
    federation_choices = []
216
    i = 0
217
    for federation in Federation.objects.all():
218
        i += i
219
        federation_choices.append(('%s' % federation, federation))
220
221
    federations = forms.MultipleChoiceField(label=_(u'Federations'), choices=federation_choices,
222
                                            help_text=_(u"Please select the federation(s) you want to gather the entity in."))
223
224
    comment = forms.CharField(max_length=1000, label=_(u"Your comment"),
225
                              help_text=_(u"Please enter your comment here."),
226
                              widget=forms.Textarea(attrs={'cols': '100', 'rows': '10'}))
227
228
    def __init__(self, *args, **kwargs):
229
        self.instance = kwargs.pop('instance')
230
        super(EntityProposalForm, self).__init__(*args, **kwargs)
231
232
        gatherd_federations = self.instance.federations.all()
233
        federation_choices = []
234
        i = 0
235
        for federation in Federation.objects.all().order_by('name'):
236
            if federation not in gatherd_federations:
237
                i += i
238
                federation_choices.append(('%s' % federation, federation))
239
240
        self.fields['federations'].widget.choices = federation_choices
241
242
    class Meta(object):
243
        exclude = []
244
245
246
class ServiceSearchForm(forms.Form):
247
    entityid = forms.CharField(max_length=200, label=_(u"Search service ID"),
248
                               help_text=_(
249
                                   u"Enter a full or partial entityid"),
250
                               widget=forms.TextInput(attrs={'size': '200'}))
251
252
    class Meta(object):
253
        exclude = []
254
255
256
class SearchEntitiesForm(forms.Form):
257
    federation_choices = [('All', 'All federations')]
258
    for federation in Federation.objects.all():
259
        federation_choices.append(('%s' % federation.id, federation))
260
261
    type_choices = [('All', 'All types')]
262
    for entity_type in EntityType.objects.all():
263
        type_choices.append(('%s' % entity_type, entity_type))
264
265
    category_choices = [('All', 'All types')]
266
    for entity_category in EntityCategory.objects.all():
267
        category_choices.append(('%s' % entity_category, entity_category))
268
269
    entity_type = forms.ChoiceField(label=_(u"Entity Type"),
270
                                    help_text=_(
271
                                        u"Select the entity type you're interest in"),
272
                                    choices=type_choices,
273
                                    initial=['All'])
274
275
    entity_category = forms.ChoiceField(label=_(u'Entity Category'),
276
                                        help_text=_(
277
                                            u"Select the entity category you're interest in"),
278
                                        choices=category_choices,
279
                                        initial=['All'])
280
281
    federations = forms.MultipleChoiceField(label=_(u"Federation filter"),
282
                                            help_text=_(
283
                                                u"Select the federations you're interest in (you may select multiple)"),
284
                                            widget=forms.CheckboxSelectMultiple,
285
                                            choices=federation_choices,
286
                                            initial=['All'])
287
288
    entityid = forms.CharField(max_length=200, label=_(u"Search entity ID"),
289
                               help_text=_(
290
                                   u"Enter a full or partial entityid"),
291
                               widget=forms.TextInput(attrs={'size': '200'}),
292
                               required=False)
293
294
    page = forms.IntegerField(min_value=0, initial=1, required=False,
295
                              widget=forms.HiddenInput(attrs={'id': 'pagination_page'}))
296
    export_format = forms.CharField(
297
        required=False, widget=forms.HiddenInput(attrs={'id': 'export_format'}))
298
299
    class Meta(object):
300
        fields = []
301