def save_config(self): """ Encode the configuration to XML and write it to disk. """ name = self.cleaned_data["name"] del self.cleaned_data["name"] config_path = os.path.join(helpers.processing_config_path(), "{}ProcessingMCP.xml".format(name)) config = PreconfiguredChoices() for choice_uuid, value in self.cleaned_data.items(): fprops = self.processing_fields.get(choice_uuid) if fprops is None or value is None: continue field = self.fields.get(choice_uuid) if field is None: continue if isinstance(field, forms.ChoiceField): if not value: # Ignore empty string! continue if fprops["type"] == "days": if value == 0: continue delay = str(float(value) * (24 * 60 * 60)) config.add_choice( choice_uuid, fprops["chain"], delay_duration=delay, comment=fprops["label"], ) elif fprops["type"] == "chain_choice" and "duplicates" in fprops: # If we have more than one chain (duplicates) then we need to # add them all, e.g.:: # # <!-- Normalize (match 1 for "Normalize for access") --> # <preconfiguredChoice> # <appliesTo>...</appliesTo> # <goToChain>...</goToChain> # </preconfiguredChoice> # <!-- Normalize (match 2 for "Normalize for access") --> # <preconfiguredChoice> # <appliesTo>...</appliesTo> # <goToChain>...</goToChain> # </preconfiguredChoice> # # Otherwise, when `KeyError` is raised, add single entry. try: desc, matches = fprops["duplicates"][value] except KeyError: config.add_choice(choice_uuid, value, comment=fprops["label"]) else: for i, match in enumerate(matches): comment = '{} (match {} for "{}")'.format( fprops["label"], i + 1, desc) config.add_choice(match[0], match[1], comment=comment) else: config.add_choice(choice_uuid, value, comment=fprops["label"]) config.save(config_path)
def delete(request, name): if name == 'default': return redirect('components.administration.views_processing.list') config_path = os.path.join(helpers.processing_config_path(), '{}ProcessingMCP.xml'.format(name)) try: os.remove(config_path) except OSError: pass return redirect('components.administration.views_processing.list')
def delete(request, name): if name == "default": return redirect("administration:processing") config_path = os.path.join(helpers.processing_config_path(), "{}ProcessingMCP.xml".format(name)) try: os.remove(config_path) except OSError: pass return redirect("administration:processing")
def processing_configurations(request): """Return list of names of available processing configurations.""" config_dir = helpers.processing_config_path() CONFIG_FILE_SUFFIX = "ProcessingMCP.xml" processing_configs = sorted([ filename[:-len(CONFIG_FILE_SUFFIX)] for filename in os.listdir(config_dir) ]) return helpers.json_response( {"processing_configurations": processing_configs})
def processing_configuration(request, name): """ Return a processing configuration XML document given its name, i.e. where name is "default" the returned file will be "defaultProcessingMCP.xml" found in the standard processing configuration directory. """ config_path = os.path.join(helpers.processing_config_path(), '{}ProcessingMCP.xml'.format(name)) if request.method == 'DELETE': try: os.remove(config_path) return helpers.json_response({'success': True}) except OSError: msg = 'No such processing config "%s".' % name LOGGER.error(msg) return helpers.json_response({ "success": False, "error": msg }, status_code=404) else: accepted_types = request.META.get('HTTP_ACCEPT', '').lower() if accepted_types != '*/*' and 'xml' not in accepted_types: return django.http.HttpResponse(status=415) try: # Attempt to read the file with open(config_path, 'r') as f: content = f.read() except IOError: # The file didn't exist, so recreate it from the builtin config try: content = install_builtin_config(name) if content: LOGGER.info('Regenerated processing config "%s".' % name) else: msg = 'No such processing config "%s".' % name LOGGER.error(msg) return helpers.json_response( { "success": False, "error": msg }, status_code=404) except Exception: msg = 'Failed to reset processing config "%s".' % name LOGGER.exception(msg) return helpers.json_response({ "success": False, "error": msg }, status_code=500) return django.http.HttpResponse(content, content_type='text/xml')
def list(request): files = [] ignored = [] for item in iglob('{}/*ProcessingMCP.xml'.format(helpers.processing_config_path())): basename = os.path.basename(item) name = re.sub('ProcessingMCP\.xml$', '', basename) if re.match(r'^\w{1,16}$', name) is None: ignored.append((basename, name, item)) continue files.append((basename, name, item)) return render(request, 'administration/processing.html', {'files': files, 'ignored': ignored})
def list(request): files = [] ignored = [] for item in iglob("{}/*ProcessingMCP.xml".format( helpers.processing_config_path())): basename = os.path.basename(item) name = re.sub("ProcessingMCP\.xml$", "", basename) if re.match(r"^\w{1,16}$", name) is None: ignored.append((basename, name, item)) continue files.append((basename, name, item)) return render(request, "administration/processing.html", { "files": files, "ignored": ignored })
def processing_configuration(request, name): """ Return a processing configuration XML document given its name, i.e. where name is "default" the returned file will be "defaultProcessingMCP.xml" found in the standard processing configuration directory. """ accepted_types = request.META.get('HTTP_ACCEPT', '').lower() if accepted_types != '*/*' and 'xml' not in accepted_types: return django.http.HttpResponse(status=415) config_path = os.path.join(helpers.processing_config_path(), '{}ProcessingMCP.xml'.format(name)) try: with open(config_path, 'r') as f: content = f.read() return django.http.HttpResponse(content, content_type='text/xml') except IOError: raise django.http.Http404
def load_config(self, name): """ Bound the choices found in the XML document to the form fields. """ self.fields["name"].initial = name self.fields["name"].widget.attrs["readonly"] = "readonly" config_path = os.path.join(helpers.processing_config_path(), "{}ProcessingMCP.xml".format(name)) root = etree.parse(config_path) for choice in root.findall(".//preconfiguredChoice"): applies_to = choice.findtext("appliesTo") go_to_chain = choice.findtext("goToChain") fprops = self.processing_fields.get(applies_to) field = self.fields.get(applies_to) if fprops is None or go_to_chain is None or field is None: continue field.initial = go_to_chain
def save_config(self): """ Encode the configuration to XML and write it to disk. """ name = self.cleaned_data['name'] del self.cleaned_data['name'] config_path = os.path.join(helpers.processing_config_path(), '{}ProcessingMCP.xml'.format(name)) config = PreconfiguredChoices() for choice_uuid, value in self.cleaned_data.items(): fprops = self.processing_fields.get(choice_uuid) if fprops is None or value is None: continue field = self.fields.get(choice_uuid) if field is None: continue if isinstance(field, forms.ChoiceField): if not value: # Ignore empty string! continue if fprops['type'] == 'days': if value == 0: continue delay = str(float(value) * (24 * 60 * 60)) config.add_choice(choice_uuid, fprops['chain'], delay_duration=delay, comment=fprops['label']) elif fprops['type'] == 'chain_choice' and fprops.get( 'find_duplicates', False): # Persist the choice made by the user for each of the existing # chain links with the same name. See #10216 for more details. try: choice_name = models.MicroServiceChain.objects.get( id=value).description except models.MicroServiceChainLink.DoesNotExist: pass else: for i, item in enumerate( get_duplicated_choices(fprops['label'], choice_name)): comment = '{} (match {} for "{}")'.format( fprops['label'], i + 1, choice_name) config.add_choice(item[0], item[1], comment=comment) else: config.add_choice(choice_uuid, value, comment=fprops['label']) config.save(config_path)
def load_config(self, name): """ Bound the choices found in the XML document to the form fields. """ self.fields['name'].initial = name self.fields['name'].widget.attrs['readonly'] = 'readonly' config_path = os.path.join(helpers.processing_config_path(), '{}ProcessingMCP.xml'.format(name)) root = etree.parse(config_path) for choice in root.findall('.//preconfiguredChoice'): applies_to = choice.findtext('appliesTo') go_to_chain = choice.findtext('goToChain') fprops = self.processing_fields.get(applies_to) field = self.fields.get(applies_to) if fprops is None or go_to_chain is None or field is None: continue if fprops['type'] == 'days': field.initial = int(float( choice.findtext('delay'))) // (24 * 60 * 60) else: field.initial = go_to_chain
def save_config(self): """ Encode the configuration to XML and write it to disk. """ name = self.cleaned_data['name'] del self.cleaned_data['name'] config_path = os.path.join(helpers.processing_config_path(), '{}ProcessingMCP.xml'.format(name)) config = PreconfiguredChoices() for choice_uuid, value in self.cleaned_data.items(): fprops = self.processing_fields.get(choice_uuid) if fprops is None or value is None: continue field = self.fields.get(choice_uuid) if field is None: continue if isinstance(field, forms.ChoiceField): if not value: # Ignore empty string! continue if fprops['type'] == 'days': if value == 0: continue delay = str(float(value) * (24 * 60 * 60)) config.add_choice(choice_uuid, fprops['chain'], delay_duration=delay, comment=fprops['label']) elif fprops['type'] == 'chain_choice' and 'duplicates' in fprops: desc, matches = fprops['duplicates'][value] for i, match in enumerate(matches): comment = '{} (match {} for "{}")'.format( fprops['label'], i + 1, desc) config.add_choice(match[0], match[1], comment=comment) else: config.add_choice(choice_uuid, value, comment=fprops['label']) config.save(config_path)
def download(request, name): config_path = os.path.join(helpers.processing_config_path(), "{}ProcessingMCP.xml".format(name)) if not os.path.isfile(config_path): raise Http404 return helpers.send_file(request, config_path, force_download=True)