def from_sentences(self, title_sentences, content_sentences): document = objectify.Element("document") document.sentences = objectify.Element("sentences") sentences_element = self.process_sentences(title_sentences, "title", "title") + \ self.process_sentences(content_sentences, "content", "bodyText") document.sentences.sentence = sentences_element self.root.append(document)
def catalog_xml(): ''' Returns an XML-serialized representation of the catalog database: ''' root = objectify.Element("catalog") categories = db.session.query(views.Category).all() for category in categories: category_element = objectify.Element(category.name, id=str(category.id)) #NOQA items = db.session.query( views.Item).filter_by(category_id=category.id).all() #NOQA for item in items: item_element = objectify.Element(item.name, id=str(item.id), description=item.description, category_id=str( item.category_id)) #NOQA category_element.append(item_element) root.append(category_element) objectify.deannotate(root, pytype=True, xsi=True) xml = etree.tostring(root, pretty_print=True) response = make_response(xml) response.headers['Content-Type'] = 'application/xml' return response
def to_xml_object(self): event = objectify.Element('Event') for field in [ 'uuid', 'distribution', 'threat_level_id', 'org', 'orgc', 'date', 'info', 'published', 'analysis', 'timestamp', 'distribution', 'proposal_email_lock', 'locked', 'publish_timestamp', 'id', 'attribute_count' ]: val = getattr(self, field) setattr(event, field, val) try: for shadowattribute in event.shadowattributes: event.append(shadowattribute.to_xml_object()) except Exception: pass for attr in self.attributes: event.append(attr.to_xml_object()) for obj in self.objects: event.append(obj.to_xml_object()) org = objectify.Element('Org') org.name = self.org event.append(org) orgc = objectify.Element('Orgc') orgc.name = self.orgc event.append(orgc) return event
def reinitL3_Tile(self, tileId): ''' Reinit an L3 tile :param tileId: the tile ID :type tileId: string ''' L3_MTD_MASK = 'S2A_*_MTD_L03_TL_*.xml' L3_TARGET_DIR = self.config.L3_TARGET_DIR GRANULE = 'GRANULE' self.config.L3_TILE_ID = tileId L3_TILE_ID = os.path.join(L3_TARGET_DIR, GRANULE, tileId) dirlist = sorted(os.listdir(L3_TILE_ID)) for L3_TILE_MTD_XML in dirlist: if fnmatch.fnmatch(L3_TILE_MTD_XML, L3_MTD_MASK): self.config.L3_TILE_MTD_XML = os.path.join( L3_TILE_ID, L3_TILE_MTD_XML) break # append the QI headers for the new resolutions: xp = L3_XmlParser(self.config, 'T03') qii = xp.getRoot('Quality_Indicators_Info') node = objectify.Element('L3_Pixel_Level_QI') if self.insert(qii, node): xp.export() node = objectify.Element('L3_Classification_QI') if self.insert(qii, node): xp.export() node = objectify.Element('L3_Mosaic_QI') if self.insert(qii, node): xp.export() return
def generateParkingRerouter(scenario_dir, parkingAreas_on, parkingAreas_off, parkingAreas_drop_off, edges, reallocate_percentage=None): edges_str = '' for edge in edges: edges_str = edges_str + edge.getID() + ' ' edges_str = edges_str[:-1] if scenario_dir[-1] == 'b' or (scenario_dir[-1] == '3' and scenario_3_case == '3'): file_path = scenario_dir + "/rerouter/reroute_parking_" + str( drop_off_only_percentage) + "_drop-off_only_" + str( reallocate_percentage) + "_reallocation.xml" else: file_path = scenario_dir + "/rerouter/reroute_parking_" + str( drop_off_only_percentage) + "_drop-off_only.xml" with open(file_path, "w") as xml_writer: xml_writer.write('''<?xml version="1.0" encoding="UTF-8"?>\n''') xml_writer.write( '''<additional xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://sumo.dlr.de/xsd/additional_file.xsd">\n''' ) for parkingAreas, type in zip( [parkingAreas_on, parkingAreas_off, parkingAreas_drop_off], ['on', 'off', 'drop_off']): rerouter_id = 'rerouter_' + type rerouter = objectify.Element("rerouter") rerouter.set("id", rerouter_id) rerouter.set("vType", type) rerouter.set("edges", edges_str) interval = objectify.Element("interval") interval.set("begin", "0") interval.set("end", "100000") for parkingArea in parkingAreas: parkingAreaID = parkingAreas[parkingArea].attrib["id"] parkingAreaOBJ = objectify.Element("parkingAreaReroute") parkingAreaOBJ.set("id", parkingAreaID) interval.append(parkingAreaOBJ) rerouter.append(interval) objectify.deannotate(rerouter) etree.cleanup_namespaces(rerouter) obj_xml = etree.tostring(rerouter, pretty_print=True, xml_declaration=False, encoding="utf-8").decode("utf-8") xml_writer.write(obj_xml) xml_writer.write('''</additional>''') xml_writer.close() print('Generate parking rerouting done.')
def _make_request_filter_data(self, criterias: list): # use objectify request_data = objectify.Element("ServiceRequest") request_data.filters = objectify.Element("ServiceRequestFilters") for c in criterias: request_data.filters.append(c) objectify.deannotate(request_data) etree.cleanup_namespaces(request_data) obj_xml = etree.tostring(request_data, pretty_print=True, xml_declaration=True) return obj_xml
def WriteConfigToFile(self): print("Записываем файл настроек...") settings_lxml = objectify.Element("settings") for setting in self.all.values(): setting_lxml = objectify.Element(setting.Name) setting_lxml.Name = setting.Name setting_lxml.Value = setting.Value setting_lxml.Invite = setting.Invite setting_lxml.Input_dict = setting.Input_dict settings_lxml.append(setting_lxml) et = etree.ElementTree(settings_lxml) et.write("config.xml", pretty_print=True)
def _make_webapp_data(self, name, url): # use objectify request_data = objectify.Element("ServiceRequest") request_data.data = objectify.Element("ServiceRequestData") request_data.data.WebApp = objectify.Element("WebApp") request_data.data.WebApp.name = name request_data.data.WebApp.url = url objectify.deannotate(request_data) etree.cleanup_namespaces(request_data) obj_xml = etree.tostring(request_data, pretty_print=True, xml_declaration=True) return obj_xml
def __init__(self, key_or_doc, name=None): if type(key_or_doc) is objectify.ObjectifiedElement: self.new = False self._set_xml_obj(key_or_doc) elif name is None: raise Exception( 'Invalid new repository; must supply key AND name (name is missing)' ) else: self.new = True self.xml = objectify.Element('repository') self.data = etree.SubElement(self.xml, 'data') self.data.id = key_or_doc self.data.name = name self.data.repoType = 'hosted' self.data.writePolicy = WRITE_POLICIES.read_write self.data.exposed = 'true' self.data.browseable = 'true' self.data.indexable = 'true' self.data.downloadRemoteIndexes = 'false' self.data.provider = 'maven2' self.data.format = 'maven2' self.data.providerRole = 'org.sonatype.nexus.proxy.repository.Repository' self.data.checksumPolicy = CHECKSUM_POLICIES.warn self.data.repoPolicy = REPO_POLICIES.release
def splitDropoffAndOnParking(total_parking_xml, drop_off_only_percentage): root = etree.parse(total_parking_xml).getroot() additional = objectify.Element("additional") for parking in root.getchildren(): if np.random.random() < 1 - drop_off_only_percentage: additional.append(parking) return additional
def writeGEXF(self, filename): gexfE = ET.Element('gexf', {'version': '1.3'}) graphE = ET.SubElement(gexfE, 'graph', { 'defaultedgetype': 'undirected', 'idtype': 'string', 'type': 'static' }) attrsE = ET.SubElement(graphE, 'attributes', { 'class': 'node', 'mode': 'static' }) for attr in self.nodeList[0].attributes: ET.SubElement(attrsE, 'attribute', { 'id': attr, 'title': attr, 'type': 'string' }) nodesE = ET.SubElement(graphE, 'nodes', {'count': str(len(self.nodeList))}) idCount = 0 for node in self.nodeList: nodeE = ET.SubElement(nodesE, 'node', { 'id': node.label, 'label': node.label, }) attvalues = ET.SubElement(nodeE, 'attvalues') for attr in node.attributes: ET.SubElement(attvalues, 'attvalue', { 'for': attr, 'value': ';'.join(node.attributes[attr]), }) idCount += 1 print('Total %d nodes' % idCount) edges = ET.SubElement(graphE, 'edges', {'count': str(len(self.edgeList))}) idCount = 0 for link in self.edgeList: edgeE = ET.SubElement( edges, 'edge', { 'id': str(idCount), 'source': link.source, 'target': link.target, 'weight': str(link.weight), }) attvaluesE = ET.SubElement(edgeE, 'attvalues') for attr in link.common: ET.SubElement(attvaluesE, 'attvalue', { 'for': attr, 'value': ';'.join(link.common[attr]), }) idCount += 1 print('Total %d edges' % idCount) tree = etree.ElementTree(gexfE) tree.write(filename + '.gexf', encoding='utf-8', xml_declaration=True)
def publish(): form = PublishForm() if form.validate_on_submit(): deviceName = str(form.name.data) deviceId = str(form.did.data) location = str(form.location.data) deviceType = str(form.dtype.data) deviceNode = objectify.Element("Device") deviceNode.name = deviceName deviceNode.id = deviceId deviceNode.location = location deviceNode.type = deviceType deviceNode.value = random.uniform(0,100) doc = etree.parse(".\generated\DeviceList-a.xml") xmlRoot=doc.getroot() xmlRoot.append(deviceNode) objectify.deannotate(xmlRoot) etree.cleanup_namespaces(xmlRoot) xmlfp = open('.\generated\DeviceList-a.xml', 'w') xmlstr = etree.tostring(xmlRoot, pretty_print=True, xml_declaration=True) xmlstr=xmlstr.decode("utf-8") xmlfp.write(xmlstr) xmlfp.close() return redirect(url_for('index')) return render_template('MAWSPublish.html', form=form)
def set_ordination_variables(self, records): # Create a new XML tree of these pairs new_ov_elem = objectify.Element('ordination_variables') for record in records: child = etree.SubElement(new_ov_elem, 'ordination_variable') if isinstance(record, np.core.records.record): child.variable_name = record.VARIABLE_NAME child.variable_path = record.VARIABLE_PATH if record.MODEL_YEAR == 0: child.set('variable_type', 'STATIC') else: child.set('variable_type', 'TEMPORAL') child.set('model_year', str(record.MODEL_YEAR)) elif isinstance(record, tuple): child.variable_name = record[0] child.variable_path = record[1] if record[2] == 0: child.set('variable_type', 'STATIC') else: child.set('variable_type', 'TEMPORAL') child.set('model_year', str(record[2])) else: err_msg = 'Record is neither a numpy recarray record or ' err_msg += 'tuple' raise ValueError(err_msg) # Replace the old XML tree with the newly created one ov_elem = self.op_elem.ordination_variables parent = ov_elem.getparent() parent.replace(ov_elem, new_ov_elem)
def plot_image_crosswalk(self, records): if self.model_type in self.imagery_model_types: # Create a new XML tree of these pairs new_pi_crosswalk_elem = objectify.Element('plot_image_crosswalk') for record in records: child = \ etree.SubElement(new_pi_crosswalk_elem, 'plot_image_pair') if isinstance(record, np.core.records.record): child.plot_year = record.PLOT_YEAR child.image_year = record.IMAGE_YEAR elif isinstance(record, tuple): child.plot_year = record[0] child.image_year = record[1] else: err_msg = 'Record is neither a numpy recarray record or ' err_msg += 'tuple' raise ValueError(err_msg) # Replace the old XML tree with the newly created one pi_crosswalk_elem = self.model_type_elem.plot_image_crosswalk parent = pi_crosswalk_elem.getparent() parent.replace(pi_crosswalk_elem, new_pi_crosswalk_elem) else: raise NotImplementedError
def CreateXmlFile(self, file_name, params): with open(file_controller.FullPath('template')) as file: xml_template = file.read() file.close() parameters = params root = objectify.fromstring(xml_template) root.set("name", file_name) counter = 0 ## Set Exist Parameters for param in parameters: for xml_param in root.settings.param: if (param['name'] == xml_param.get("name")): xml_param.set('value', param['value']) del parameters[counter] counter += 1 ## Add New Parameters for param in parameters: root.settings.append( objectify.Element("param", name=param['name'], value=param['value'])) return etree.tostring(root)
def parse_data(self, raw_data): channels = raw_data.channel current_program_guide = objectify.Element('program_guide') search_day_programme = etree.XPath( '//programme[starts-with(@start, "20200504")]') for event in search_day_programme(raw_data): current_program_guide.append(event) search_program = etree.XPath('//programme[@channel = $channel_id]') data: List[EPGChannel] = list() for channel in channels: channel_id = channel.attrib['id'] channel_events: List[EPGEvent] = list() events = search_program(current_program_guide, channel_id=channel_id) if not events: continue for event in events: event_disc = EPGEvent( datetime(1, 1, 1, int(event.attrib['start'][8:10]), int(event.attrib['start'][10:12])), datetime(1, 1, 1, int(event.attrib['stop'][8:10]), int(event.attrib['stop'][10:12])), event.title) channel_events.append(event_disc) data.append(EPGChannel(channel['display-name'], channel_events)) return data
def search(self, value=None, type=None, category=None, tag=None, fromd=None, tod=None, last=None): """ Searches an attribute on the MISP server :param value: value of the attribute to be searched (as a string) :param type: Type of the attribute to be searched (as a string) :param category: Category of the attribute to be searched (as a string) :param tag: To include a tag in the results just write its names into this parameter. To exclude a tag prepend it with a '!'. You can also chain several tag commands together with the '&&' operator. Please be aware the colons (:) cannot be used in the tag search. Use semicolons instead (the search will automatically search for colons instead). :param fromd: Events with the date set to a date after the one specified in the from field (format: 2015-02-15). This filter will use the date of the event. :param tod: Events with the date set to a date before the one specified in the to field (format: 2015-02-15). This filter will use the date of the event. :param last: Events published within the last x amount of time, where x can be defined in days, hours, minutes (for example 5d or 12h or 30m). This filter will use the published timestamp of the event. .. todo:: support by type/category/tags :example: >>> server = MispServer() >>> attr = server.attributes.search("google.com") [MispEvent, MispEvent...] """ request = objectify.Element('request') if value: request.value = value if type: request.type = type if category: request.category = category if tag: request.tag = tag if fromd: setattr(request, 'from', fromd) if tod: request.to = tod if last: request.last = last lxml.objectify.deannotate(request, xsi_nil=True) lxml.etree.cleanup_namespaces(request) raw = lxml.etree.tostring(request) try: raw = self.server.POST('/events/restSearch/download', raw) except MispTransportError as err: if err[2] == 404: # 404 not found return [] else: # Other problem keep the exception raise err response = objectify.fromstring(raw) events = [] for evtobj in response.Event: events.append(MispEvent.from_xml_object(evtobj)) return events
def __init__(self, document=None): """Initialize constructor for MavenPom class. :document: Parse the content of the file. :returns: None """ if not document: raise ValueError("No content is provided for parsing") self.document = document.strip() if not isinstance(self.document, (bytes, bytearray)): self.document = self.document.encode() self.root = objectify.fromstring(self.document) # create a dependencies element if doesn't exist if getattr(self.root, 'dependencies', None) is None: _prev = getattr(self.root, 'dependencyManagement', None)\ or getattr(self.root, 'properties', None)\ or getattr(self.root, 'name', None) if _prev is not None: _prev.addnext(objectify.Element('dependencies')) else: self.root.dependencies = objectify.ObjectifiedElement() self.root = self._reload(self.root) self.dependency_set = set([ self.Dependency(d) for d in getattr(self.root.dependencies, 'dependency', []) ])
def Add_Node(*arg): global root # new "instance" of a children of a root newEle = objectify.Element("pelicula") newEle.titulo = arg[0] newEle.guionista = arg[1] newEle.productora = arg[2] newEle.director = arg[3] newEle.actor = arg[4] newEle.sinopsis = arg[5] # append to root scope a new children root.append(newEle) # Clean unnecessary attributes objectify.deannotate(newEle, pytype=True, xsi=True, xsi_nil=True, cleanup_namespaces=True) # Initalize the new xml string newXml = etree.tostring(root, pretty_print=True) # write the whole xml in a new doc with open("new6.xml", "bw") as target: target.write(newXml)
def __init__(self, tag, values, attribs, elem=None): """Constructor. @type tag: str @param tag: The XML-tag to use to represent an instance of this model @type values: list @param values: A list of names of accepted the child values @type attribs: list @param attribs: A list of accepted attributes @type elem: lxml.objectify.ObjectifiedElement @param elem: The XML element wrapped by the model """ assert isinstance(tag, str) and len(tag) > 0 # Bypass XMLModel.__setattr__() super_set = super(XMLModel, self).__setattr__ super_set('tag', tag) super_set('values', values) super_set('attribs', attribs) if elem is None: super_set('elem', objectify.Element(tag)) else: super_set('elem', elem) super(XMLModel, self).__init__()
def curate_response(response): try: o = objectify.fromstring(response) assert o.tag == 'CAT-API-Response' return o except (XMLSyntaxError, AssertionError): return objectify.Element('Dummy')
def create_object(root, name): obj = objectify.Element("object") obj.set("name", name) obj.title = name obj.append( dict2xml("meta", { "authors": {"author": "Serge Poltavski"}, "description": " ", "license": "GPL3 or later", "library": "ceammc", "category": name.split('.')[0], "keywords": "", "since": VERSION, "also": {"see": " "} }) ) obj.append( dict2xml("arguments", { "argument": " " }) ) obj.append( dict2xml("properties", { "property": " " }) ) root.append(obj)
def set_read_sms(msg_id): msg_index = [] if isinstance(msg_id, int): msg_index.append(str(msg_id)) elif isinstance(msg_id, str): msg_index.append(msg_id) else: msg_index = msg_id sent = 0 if len(msg_index) > 0: for i in msg_index: # print("set read: ", i) request = objectify.Element("request") request.Index = i payload = etree.tostring(request) # print(payload) a = requests.post(E303_ip + HTTPPOST_SET_READ, data=payload) # print (a.text) # print (a.status_code) if a.status_code == 200: if get_word(a.text, "OK"): sent += 1 if sent == len(msg_index): return True return False
def process_sentences(self, sentences, section_name, section_type): def process_sentence(sent): tokens = objectify.Element("tokens") tokens_element = [] for token in sent: token_id = token["id"] token_element = objectify.Element("token", id=str(token_id)) token_element.word = token["word"] token_element.lemma = token["lemma"] token_element.CharacterOffsetBegin = token[ "character_offset_begin"] token_element.CharacterOffsetEnd = token[ "character_offset_end"] token_element.POS = token["pos"] token_element.deprel = token["deprel"] token_element.deprel_head_id = token["deprel_head_id"] token_element.deprel_head_text = token["deprel_head_text"] if "term_tag" in token: token_element.term_tag = token["term_tag"] token_element.ner = token["ner"] tokens_element.append(token_element) tokens.token = tokens_element return tokens sentences_element = [] for sentence in sentences: sentence_element = objectify.Element("sentence", section=section_name, type=section_type, id=str(self.sentence_id)) sentence_element.tokens = process_sentence(sentence) sentences_element.append(sentence_element) self.sentence_id += 1 return sentences_element
def search(self, attr_type=None, tags=None, value=None, category=None, org=None, date_from=None, date_to=None, last=None, quickfilter=None, evtid=None): """Search events on the MISP server. Searching criteria: :param attr_type: The attribute type, any valid MISP attribute type is accepted. :param tags: To include a tag in the results just write its names into this parameter. To exclude a tag prepend it with a '!'. You can also chain several tag commands together with the '&&' operator. Please be aware the colons (:) cannot be used in the tag search. Use semicolons instead (the search will automatically search for colons instead). :param value: Search for the given value in the attributes' value field. :param category: The attribute category, any valid MISP attribute category is accepted. :param org: Search by the creator organisation by supplying the organisation idenfitier. :param date_from: Events with the date set to a date after the one specified in the from field (format: 2015-02-15) :param date_to: Events with the date set to a date before the one specified in the to field (format: 2015-02-15) :param last: Events published within the last x amount of time, where x can be defined in days, hours, minutes (for example 5d or 12h or 30m) :param quickfilter: Enabling this (by passing "1" as the argument) will make the search ignore all of the other arguments, except for the auth key and value. :param evtid: :returns: List of :class:`MispEvent` objects """ request = objectify.Element('request') #request.searchall = 1 if attr_type: request.type = attr_type if evtid: request.evtid = evtid if tags: request.tags = tags if value: request.value = value if category: request.category = category if org: request.org = org if date_to: request.date_to = date_to if date_from: request.date_from = date_from if last: request.last = last if quickfilter: request.quickfilter = quickfilter lxml.objectify.deannotate(request, xsi_nil=True) lxml.etree.cleanup_namespaces(request) raw = lxml.etree.tostring(request) raw = self.server.POST('/events/restSearch/download', raw) response = objectify.fromstring(raw) events = [] for evtobj in response.Event: events.append(MispEvent.from_xml_object(evtobj)) return events
def Param(name, value=None, unit=None, ucd=None, dataType=None, utype=None, ac=True): """ 'Parameter', used as a general purpose key-value entry in the 'What' section. May be assembled into a :class:`Group`. NB ``name`` is not mandated by schema, but *is* mandated in full spec. Args: value(str): String representing parameter value. Or, if ``ac`` is true, then 'autoconversion' is attempted, in which case ``value`` can also be an instance of one of the following: * :py:obj:`bool` * :py:obj:`int` * :py:obj:`float` * :py:class:`datetime.datetime` This allows you to create Params without littering your code with string casts, or worrying if the passed value is a float or a string, etc. NB the value is always *stored* as a string representation, as per VO spec. unit(str): Units of value. See :class:`.definitions.units` ucd(str): `unified content descriptor <http://arxiv.org/abs/1110.0525>`_. For a list of valid UCDs, see: http://vocabularies.referata.com/wiki/Category:IVOA_UCD. dataType(str): Denotes type of ``value``; restricted to 3 options: ``string`` (default), ``int`` , or ``float``. (NB *not* to be confused with standard XML Datatypes, which have many more possible values.) utype(str): See http://wiki.ivoa.net/twiki/bin/view/IVOA/Utypes ac(bool): Attempt automatic conversion of passed ``value`` to string, and set ``dataType`` accordingly (only attempted if ``dataType`` is the default, i.e. ``None``). (NB only supports types listed in _datatypes_autoconversion dict) """ # We use locals() to allow concise looping over the arguments. atts = locals() atts.pop('ac') temp_dict = {} temp_dict.update(atts) for k in temp_dict.keys(): if atts[k] is None: del atts[k] if (ac and value is not None and (not isinstance(value, string_types)) and dataType is None): if type(value) in _datatypes_autoconversion: datatype, func = _datatypes_autoconversion[type(value)] atts['dataType'] = datatype atts['value'] = func(value) return objectify.Element('Param', attrib=atts)
def create_phonebook_gs(users): xml = '''<?xml version="1.0" encoding="UTF-8"?><AddressBook></AddressBook>''' root = objectify.fromstring(xml) for phone,u_prm in users.iteritems(): contact = objectify.Element("Contact") contact.FirstName = u_prm[1].decode('utf8') xml_phone = objectify.Element("Phone") xml_phone.phonenumber = phone xml_phone.accountindex = 1 contact.append(xml_phone) xml_group = objectify.Element("Groups") xml_group.groupid = 0 contact.append(xml_group) root.append(contact) objectify.deannotate(root) etree.cleanup_namespaces(root) obj_xml = etree.tostring(root, pretty_print=True, xml_declaration=True, encoding='utf8') return obj_xml
def to_xml_object(self): attr = objectify.Element('Attribute') for field in [ 'distribution', 'type', 'category', 'to_ids', 'comment', 'value', 'event_id', 'timestamp', 'uuid', 'id' ]: val = getattr(self, field) setattr(attr, field, val) return attr
def create_e1afvol(data): appt = objectify.Element("E1AFVOL") appt.VORNR = data["VORNR"] appt.LTXA1 = data["LTXA1"] appt.ARBID = data["ARBID"] appt.MGVRG = data["MGVRG"] appt.MEINH = data["MEINH"] appt.LMNGA = data["LMNGA"] return appt
def reinitL3_TargetProduct(self): ''' Reinit the L3 target product :return: true if succesful :rtype: bool ''' L3_DS_ID = None L3_TARGET_MASK = '*L03_*' dirlist = sorted(os.listdir(self.config.targetDir)) for L3_TARGET_ID in dirlist: if fnmatch.fnmatch(L3_TARGET_ID, L3_TARGET_MASK) == True: self.config.L3_TARGET_ID = L3_TARGET_ID self.config.L3_TARGET_DIR = os.path.join( self.config.targetDir, L3_TARGET_ID) break # create user product: filelist = sorted(os.listdir(self.config.L3_TARGET_DIR)) found = False for filename in filelist: if (fnmatch.fnmatch(filename, 'MTD_MSIL03.xml') == True): found = True break if found == False: stderrWrite('No metadata for user product') self.config.exitError() self.config.L3_TARGET_MTD_XML = os.path.join(self.config.L3_TARGET_DIR, filename) xp = L3_XmlParser(self.config, 'UP03') l3qii = xp.getRoot('Quality_Indicators_Info') node = objectify.Element('Classification_QI') node.attrib['resolution'] = str(self.config.resolution) if self.insert(l3qii, node): xp.export() L3_DS_MASK = 'DS_*' DATASTRIP = 'DATASTRIP' L3_DS_DIR = os.path.join(self.config.targetDir, L3_TARGET_ID, DATASTRIP) dirlist = sorted(os.listdir(L3_DS_DIR)) for L3_DS_ID in dirlist: if fnmatch.fnmatch(L3_DS_ID, L3_DS_MASK) == True: self.config.L3_DS_ID = L3_DS_ID break if L3_DS_ID is not None: L3_DS_MTD_XML = 'MTD_DS.xml' self.config.L3_DS_MTD_XML = os.path.join(L3_DS_DIR, L3_DS_ID, L3_DS_MTD_XML) return True return False