def convert(self, data, cache, **kwargs): bodydom = Element('div') kmldom = XML(data) ns = kmldom.tag.strip('kml') placemarks = kmldom.findall('.//%sPlacemark' % ns) for placemark in placemarks: titles = placemark.findall(ns + 'name') for title in titles: t = Element('h2') t.text = title.text bodydom.append(t) descriptions = placemark.findall(ns+'description') for desc in descriptions: if desc.text: try: text = desc.text.encode('ascii', 'xmlcharrefreplace').strip() except: text = desc.text.strip() text = sanitize(text) d = XML('<div>' + text.encode('ascii', 'xmlcharrefreplace') + '</div>') bodydom.append(d) body = tostring(bodydom) cache.setData(body) return cache
def draw_bus(self, title, color): gelem = Element("g") # create a group oelem = Element("path") otuple = (self.x, self.y - self.height/2, self.period/8, -self.height/2, 6*self.period/8.0, self.period/8.0, self.height/2, -self.period/8, self.height/2.0, -6*self.period/8.0) oelem.attrib['d']= "M%f,%f l%f,%f h%f l%f,%f l%f,%f h%f Z" % otuple oelem.attrib['stroke'] = "black" oelem.attrib['fill'] = color oelem.attrib['stroke-linecap'] = "square" gelem.append(oelem) telem = Element("text") telem.attrib['x'] = "%f" % (self.x + self.period/2) telem.attrib['y'] = "%f" % (self.y - self.height/4.0-0.3) telem.attrib['font-family'] = "Helvetica" telem.attrib['font-size'] = "%f" % (self.height/1.9) telem.attrib['text-anchor'] = "middle" telem.text = title gelem.append(telem) self.x += self.period self.sval = 'Z' return gelem
def convert(self, data, cache, **kwargs): bodydom = Element('div') kmldom = XML(data) ns = kmldom.tag.strip('kml') placemarks = kmldom.findall('.//%sPlacemark' % ns) for placemark in placemarks: titles = placemark.findall(ns + 'name') for title in titles: t = Element('h2') t.text = title.text bodydom.append(t) descriptions = placemark.findall(ns + 'description') for desc in descriptions: if desc.text: try: text = desc.text.encode('ascii', 'xmlcharrefreplace').strip() except: text = desc.text.strip() text = sanitize(text) d = XML('<div>' + text.encode('ascii', 'xmlcharrefreplace') + '</div>') bodydom.append(d) body = tostring(bodydom) cache.setData(body) return cache
def setUp(self): from_string('<temp/>') s1 = Element('class') s1.set('name','test') t.append(s1) s2 = Element('handler') s2.text = "print 'Hi!'" s2.set('on','init') s1.append(s2) self.node1 = s1 doc2 = Element('class') doc2.set('name','test2') doc2.set('extends','test') s3 = Element('handler') s3.text = 'print Hi2!' s3.set('on','init') doc2.append(s3) self.node2 = doc2
def ToElement(self, it=None): """ Represents the store contents as an ElementTree.Element. """ if it is None: it = self.entries.iteritems() elt = Element("entities") for peer_id, entry in it: elt.append(entry.ToElement()) return elt
class ZigXmlParser(object): def __init__(self, input): self.filename = os.path.split(input)[-1] self.xmltree = parse(input).getroot() self.TODAY = date.today().isoformat() self.tag_names = [ 'ID', 'creator', 'created_date', 'modified_date', 'weight', 'aplha', 'BQP', 'BQP_buffer', 'cell_removal', 'spp_file' ] def read_element(self, element, idvalue): for target in self.xmltree.findall('feature'): if target.find('ID').text == str(idvalue): return target.find(element).text def write_element(self, element, idvalue, value): # Set modified_date for the inputset self.xmltree.find('modified_date').text = self.TODAY for target in self.xmltree.findall('feature'): if target.find('ID').text == str(idvalue): target.find(element).text = str(value) # Set modified_date for the specific element target.find('modified_date').text = self.TODAY def create_new_feature(self, location=None): self.feature = Element('feature') for elem in self.tag_names: self.feature.append(Element(elem)) if not location: self.xmltree.append(self.feature) else: self.xmltree.insert(location, self.feature) self.indent(self.xmltree) def write_xml_file(self): ElementTree(self.xmltree).write(os.getcwd() + r'\mod_' + self.filename) print os.getcwd() + r'\mod_' + self.filename def show_xml_tree(self): dump(self.xmltree) def indent(self, elem, level=0): """ Adds tab to the tree, so that saving it as usual results in a prettyprinted tree.""" i = "\n" + level * "\t" if len(elem): if not elem.text or not elem.text.strip(): elem.text = i + "\t" for elem in elem: self.indent(elem, level + 1) if not elem.tail or not elem.tail.strip(): elem.tail = i else: if level and (not elem.tail or not elem.tail.strip()): elem.tail = i
def _format(self, elemap, obj): defaults = self._defaults out = Element(elemap[0]) for subspec in elemap[1:]: if type(subspec) == type(''): tmp = obj.get(subspec, None) if tmp is None or str(tmp) == '': tmp = defaults.get(subspec, '') out.text = str(tmp) continue # here, subspec is really a recursive element map subelem = self._format(subspec, obj) out.append(subelem) return out
def body(self): """ Body exporter """ klass = self.context.__class__ factory = ".".join((klass.__module__, klass.__name__)) element = Element("object", name=self.context.__name__, factory=factory) for prop in self.properties: element.append(prop) for child in self.children: element.append(child) return element
def _format(self,elemap,obj): defaults = self._defaults out = Element(elemap[0]) for subspec in elemap[1:]: if type(subspec) == type(''): tmp = obj.get(subspec,None) if tmp is None or str(tmp) == '': tmp = defaults.get(subspec,'') out.text = str(tmp) continue # here, subspec is really a recursive element map subelem = self._format(subspec,obj) out.append(subelem) return out
def __init__(self, root, showRoot = True): QtCore.QAbstractItemModel.__init__(self) if showRoot: fakeroot = Element("fakeroot") fakeroot.append(root) self._root = fakeroot else: self._root = root self._realroot = self._root self._columns = ["Tag", "Attributes"] self._np = dict((child, (parent, rowidx)) for parent in self._root.getiterator() for rowidx, child in enumerate(parent))
def writePolygon(self, objGeo, elemPlace): elemGeo = Element('Polygon') #Now add the ring(s) dctRings = objGeo.getRingInfo() #get the external ring(s) lstOuter = objGeo.getRing('Outer') lstInner = objGeo.getRing('Inner') for x in range(0, dctRings['Outer']): elemRing = self.addRing(lstOuter[x], 'Outer') elemGeo.append(elemRing) for x in range(0, dctRings['Inner']): elemRing = self.addRing(lstInner[x], 'Inner') elemGeo.append(elemRing) return elemGeo
def add_clock(self, name, datastr): sigelem = Element('g') # this is where we get the cycle count self.cycles = len(datastr.split()) clksig = signal(name, self.xzero, self.ypos, self.period, self.height) sigelem.append(clksig.draw_name()) for i in datastr.split(): sigelem.append(clksig.draw_clock()) self.ypos += self.signalspacing + self.height self.signalselem.append(sigelem) self.signalcnt += 1
def __split_models(self, xmlDoc): """generator that takes parameter xmlDoc and splits it into many xml files, with only one model per each""" elem = XML(xmlDoc) models = elem.find("Models") if models: elem.remove(models) for model in models: to_return = copy.deepcopy(elem) new_models = Element("Models") for a in models.attrib: new_models.attrib[a] = models.attrib[a] new_models.append(model) to_return.append(new_models) yield (model.attrib['id'], to_return) else: pass #TODO return error
def encode_XMLDict(self, mapping): """!TXT!""" def encode(key, value): element = Element(key) if isinstance(value, NoneType): element.attrib['type'] = 'none' elif isinstance(value, BooleanType): element.attrib['type'] = 'bool' element.attrib['value'] = value and 'true' or 'false' elif isinstance(value, ComplexType): element.attrib['type'] = 'complex' element.attrib['re'] = repr(value.real) element.attrib['im'] = repr(value.imag) elif isinstance(value, FloatType): element.attrib['type'] = 'float' element.attrib['value'] = repr(value) elif isinstance(value, IntType): element.attrib['type'] = 'int' element.attrib['value'] = repr(value) elif isinstance(value, LongType): element.attrib['type'] = 'long' element.attrib['value'] = repr(value) elif isinstance(value, StringType) or isinstance(value, UnicodeType): element.attrib['type'] = 'cdata' element.text = u"<![CDATA[%s]]>" % value elif isinstance(value, DictType): element.attrib['type'] = 'dict' for key in value.keys(): element.append(encode(key, value[key])) elif isinstance(value, ListType): element.attrib['type'] = 'list' for subvalue in value: element.append(encode('value', subvalue)) elif isinstance(value, TupleType): element.attrib['type'] = 'tuple' for subvalue in value: element.append(encode('value', subvalue)) else: raise TypeError("Encoding of %s not supported (Key: %s)" % (repr(value), key)) return element root = Element("data") for key in mapping.keys(): root.append(self.encode(key, mapping[key])) return tostring(root)
def __MultiplyRequiredElement(self, xmlFile, xmlTreePath): ''' Multiplies the last element of the value of xmlTreePath as many times as predefined number of self.instances. ''' __name__ = '__MultiplyRequiredElement()' self.logger.debug('[%s] Accessing %s...' % (self.__Blu('i'), __name__)) if 'Gw' in xmlFile: xmlFile = pJoin(self.targetsXmlFolder, search('(^conf\..*)(_\d+)', xmlFile).group(1)) elif 'Radius' in xmlFile: xmlFile = pJoin(self.radiusXmlFolder, search('(^conf\..*)(_\d+)', xmlFile).group(1)) Mapper, InPathNodes, tree, treeRoot = self.__ObtainRequiredVariables(xmlFile, xmlTreePath) for inPathNode in InPathNodes: for counter in range(self.counterStartsFrom, self.instances + 2): if 'Gw' in xmlFile: clonedChild = Element(inPathNode.tag) for inPathNodeChild in inPathNode: if inPathNodeChild.tag == 'outboundPort': clonedChildChild = Element(inPathNodeChild.tag) clonedChild.append(clonedChildChild) clonedChildChild.text = str(int(self.defaultOutgoingPort) + self.portIncrement * (counter - 1)) elif inPathNodeChild.tag == 'inboundPort': clonedChildChild = Element(inPathNodeChild.tag) clonedChild.append(clonedChildChild) clonedChildChild.text = str(int(self.defaultIncomingPort) + self.portIncrement * (counter - 1)) else: clonedChild.append(inPathNodeChild) Mapper[inPathNode].append(clonedChild) elif 'Radius' in xmlFile: clonedChild = Element(inPathNode.tag) for inPathNodeChild in inPathNode: if inPathNodeChild.tag == 'OutboundPort': clonedChildChild = Element(inPathNodeChild.tag) clonedChild.append(clonedChildChild) clonedChildChild.text = str(int(self.defaultRadiusPort) + self.portIncrement * (counter - 1)) else: clonedChild.append(inPathNodeChild) Mapper[inPathNode].append(clonedChild) self.__ReformatXmlTree(treeRoot, 0) self.__WriteXmlTree(tree, xmlFile) return xmlFile
def draw_split(self): """ Draws a set of hashmarks at the desired level """ gelem = Element("g") # create a group level = self.sval if level == 'H': y = self.y-self.height elif level == 'Z': y = self.y - self.height/2.0 else: y = self.y l0elem = Element("line") l0elem.attrib['x1'] = str(self.x) l0elem.attrib['y1'] = str(y); l0elem.attrib['x2'] = str(self.x + 3.5 * self.period/8.0) l0elem.attrib['y2'] = str(y); l0elem.attrib['stroke'] = "black" gelem.append(l0elem) l1elem = Element("line") l1elem.attrib['x1'] = str(self.x + 3.0* self.period/8.0) l1elem.attrib['y1'] = str(y + self.height/4.0); l1elem.attrib['x2'] = str(self.x + 4*self.period/8.0) l1elem.attrib['y2'] = str(y - self.height/4.0); l1elem.attrib['stroke'] = "black" gelem.append(l1elem) l2elem = Element("line") l2elem.attrib['x1'] = str(self.x + 4.0* self.period/8.0) l2elem.attrib['y1'] = str(y + self.height/4.0); l2elem.attrib['x2'] = str(self.x + 5.0*self.period/8.0) l2elem.attrib['y2'] = str(y - self.height/4.0); l2elem.attrib['stroke'] = "black" gelem.append(l2elem) l3elem = Element("line") l3elem.attrib['x1'] = str(self.x + 4.5*self.period/8.0) l3elem.attrib['y1'] = str(y); l3elem.attrib['x2'] = str(self.x + self.period) l3elem.attrib['y2'] = str(y); l3elem.attrib['stroke'] = "black" gelem.append(l3elem) self.x += self.period return gelem
def main(): parser = argparse.ArgumentParser(add_help=False, prog='modulemng') subparsers = parser.add_subparsers(title='subcommands', help='valid subcommands', dest="sub_command") get = subparsers.add_parser('get') get.add_argument("module", help="module", default=None) list = subparsers.add_parser('list') list.add_argument("-d", help="module details", dest="details", action="store_true", default=False) help = subparsers.add_parser('help') args = parser.parse_args() if args.sub_command == "help": parser.print_help() return 0 # retrieve all modules from file system top = Element('modules') # get if args.sub_command == "get": m = searchModule(args.module) if m != None: top.append(m.toElementTree(True)) print tostring(top) return 0 print 'module not found' return 1 # list all_modules = browseModules() for type, modules in all_modules.items(): for module in modules.values(): em = module.toElementTree(args.details) top.append(em) print tostring(top) return 0
def __init__(self, root, showRoot = True): QtCore.QAbstractItemModel.__init__(self) if showRoot: fakeroot = Element("fakeroot") fakeroot.append(root.getroot()) self._root = fakeroot else: self._root = root.getroot() self._xpathroot = root self._realroot = self._root self._columns = ["Tag", "Attributes"] self._ne = {} self._np = {} self._ne[0] = self._root self.buildMaps(self._root, 0) self._neo = self._ne.copy() self._npo = self._np.copy()
def timinggrid(self): """ This function uses the signalcnt, cycles, period, height, and spacing to draw the light lines that will be the clock lines. """ gelem = Element("g") # create a group for i in range(int(self.cycles)): lelem = Element("line") lelem.attrib['x1'] = str(i*self.period + self.period/2.0 + self.xzero) lelem.attrib['y1'] = str(0); lelem.attrib['x2'] = str(i*self.period + self.period/2.0 + self.xzero) lelem.attrib['y2'] = str(self.signalcnt*(self.height + self.signalspacing) + self.signalspacing) lelem.attrib['stroke'] = "grey" lelem.attrib['stroke-width'] = "0.5" gelem.append(lelem) self.svgelem.append(gelem) self.svgelem.append(self.signalselem)
def add_signal(self, name, datastr): sigelem = Element('g') sig = signal(name, self.xzero, self.ypos, self.period, self.height) sigelem.append(sig.draw_name()) for i in datastr.split(): if i == 'H': sigelem.append(sig.draw_high()) elif i == 'L': sigelem.append(sig.draw_low()) elif i == 'Z': sigelem.append(sig.draw_z()) elif i == '//': sigelem.append(sig.draw_split()) self.ypos += self.signalspacing + self.height self.signalselem.append(sigelem) self.signalcnt += 1
def saveScriptConfig(config): """ save it into the the config """ elemConfig = Element("config") lognode = Element("logvalue") elemConfig.append(lognode) lognode.text = str(config.logvalue) mediaNode = Element("media") mediaNode.attrib["updateurl"] = config.mediaUpdateURL elemConfig.append(mediaNode) podcastNode = Element("podcast") if config.podcastDownload: podcastNode.attrib["download"] = 'true' else: podcastNode.attrib["download"] = 'false' podcastNode.attrib["localpath"] = config.podcastDownloadPath elemConfig.append(podcastNode) # create the userdata dir when not exist if not os.path.exists(CONFIG_DIR_ROOT): createDirectory(CONFIG_DIR_ROOT, recursive=True) #if os.path.exists(CONFIG_DIR): createXmlFile(CONFIG_FULL_PATH, elemConfig) #, encoding='ascii')
def main(): parser = argparse.ArgumentParser(add_help=False, prog="modulemng") subparsers = parser.add_subparsers(title="subcommands", help="valid subcommands", dest="sub_command") get = subparsers.add_parser("get") get.add_argument("module", help="module", default=None) list = subparsers.add_parser("list") list.add_argument("-d", help="module details", dest="details", action="store_true", default=False) help = subparsers.add_parser("help") args = parser.parse_args() if args.sub_command == "help": parser.print_help() return 0 # retrieve all modules from file system top = Element("modules") # get if args.sub_command == "get": m = searchModule(args.module) if m != None: top.append(m.toElementTree(True)) print tostring(top) return 0 print "module not found" return 1 # list all_modules = browseModules() for type, modules in all_modules.items(): for module in modules.values(): em = module.toElementTree(args.details) top.append(em) print tostring(top) return 0
def __call__(self): s = Element("settings") f = Element("filters") f.text = self.context.extra_filters s.append(f) p = Element("verp_prefix") p.text = self.context.verp_prefix s.append(p) e_ns = Element("newsletters") for nl in self.context.objectValues("Newsletter"): n = Element("newsletter") n.text = nl.id e_ns.append(n) s.append(e_ns) return tostring(s, 'utf-8')
def new_tree_term(termIdentifier, caption, description): term = Element(ns + 'term') treeTermIdentifier = Element(ns + 'termIdentifier') treeTermIdentifier.text = termIdentifier term.append(treeTermIdentifier) treeCaption = Element('caption') addLangs(treeCaption, caption) term.append(treeCaption) treeDesc = Element('description') addLangs(treeDesc, description) term.append(treeDesc) return term
def new_tree_term(self, termIdentifier, caption, description): term = Element(NS + "term") treeTermIdentifier = Element(NS + "termIdentifier") treeTermIdentifier.text = termIdentifier term.append(treeTermIdentifier) treeCaption = Element(NS + "caption") self.addLangs(treeCaption, caption) term.append(treeCaption) treeDesc = Element("description") self.addLangs(treeDesc, description) term.append(treeDesc) return term
def new_tree_term(self, termIdentifier, caption, description): term = Element(NS + 'term') treeTermIdentifier = Element(NS + 'termIdentifier') treeTermIdentifier.text = termIdentifier term.append(treeTermIdentifier) treeCaption = Element(NS + 'caption') self.addLangs(treeCaption, caption) term.append(treeCaption) treeDesc = Element('description') self.addLangs(treeDesc, description) term.append(treeDesc) return term
def add_bus(self, name, datastr, classstr): sigelem = Element('g') sig = signal(name, self.xzero, self.ypos, self.period, self.height) sigelem.append(sig.draw_name()) color = "white" data = datastr.split() if classstr != None: classes = classstr.split() for i in range(len(data)): cyccolor = color if len(classes) == 0: cl = 0 else: cl = classes[i] if self.classes.has_key(cl): cyccolor = self.classes[cl] else: cyccolor = self.colors.pop(0) self.classes[cl] = cyccolor if data[i] =='//': sigelem.append(sig.draw_split()) elif data[i] == 'Z': sigelem.append(sig.draw_z()) else: sigelem.append(sig.draw_bus(data[i], cyccolor)) self.ypos += self.signalspacing + self.height self.signalselem.append(sigelem) self.signalcnt += 1
def run(self, root): root = self.create_source(root) root = self.create_effects(root) i = 1 nodes = [] buf = [] slide = Element('div') slide_node = Element('div') # finding and creating slides from H1 and H2 for c in root: if c.tag in ('h1','h2'): # append previous slide_node if (slide_node!=None): slide.append(slide_node) # create a new one for this title slide_node = self.create_slide(buf,i,c.text) slide_node.append(c) else: # append this to the slide div slide_node.append(c) return slide
class ZigXmlParser(object): def __init__(self, input): self.filename = os.path.split(input)[-1] self.xmltree = parse(input).getroot() self.TODAY = date.today().isoformat() self.tag_names = ['ID', 'creator', 'created_date', 'modified_date', 'weight', 'aplha', 'BQP', 'BQP_buffer', 'cell_removal', 'spp_file'] def read_element(self, element, idvalue): for target in self.xmltree.findall('feature'): if target.find('ID').text == str(idvalue): return target.find(element).text def write_element(self, element, idvalue, value): # Set modified_date for the inputset self.xmltree.find('modified_date').text = self.TODAY for target in self.xmltree.findall('feature'): if target.find('ID').text == str(idvalue): target.find(element).text = str(value) # Set modified_date for the specific element target.find('modified_date').text = self.TODAY def create_new_feature(self, location=None): self.feature = Element('feature') for elem in self.tag_names: self.feature.append(Element(elem)) if not location: self.xmltree.append(self.feature) else: self.xmltree.insert(location, self.feature) self.indent(self.xmltree) def write_xml_file(self): ElementTree(self.xmltree).write(os.getcwd() + r'\mod_' + self.filename) print os.getcwd() + r'\mod_' + self.filename def show_xml_tree(self): dump(self.xmltree) def indent(self, elem, level=0): """ Adds tab to the tree, so that saving it as usual results in a prettyprinted tree.""" i = "\n" + level * "\t" if len(elem): if not elem.text or not elem.text.strip(): elem.text = i + "\t" for elem in elem: self.indent(elem, level+1) if not elem.tail or not elem.tail.strip(): elem.tail = i else: if level and (not elem.tail or not elem.tail.strip()): elem.tail = i
elem.text = msg element.append(elem) #ugly way to find the right position for adding our stuff termIdBefore = [ x for x in tree.findall('.//%stermIdentifier' % ns) if x.text == 'stress' ][0] termBefore = [x for x in tree.getroot() if len(x) and x[0] == termIdBefore][0] term_position = [x for x in tree.getroot()].index(termBefore) # XML Creation new_root_element = Element(ns + 'term') termIdentifier = Element(ns + 'termIdentifier') termIdentifier.text = 'whp' new_root_element.append(termIdentifier) caption = Element(ns + 'caption') addLangs(caption, 'Workplace Health Promotion') new_root_element.append(caption) for key, value in tags.items(): new_element = Element(ns + 'term') termIdentifier = Element(ns + 'termIdentifier') termIdentifier.text = key new_element.append(termIdentifier) caption = Element(ns + 'caption') addLangs(caption, value) new_element.append(caption) new_root_element.append(new_element) tree.getroot().insert(term_position + 1, new_root_element) # you have to strip the ns0 and beautify it
et.parse(fpath) version = et.getroot().get("version") if not version: print "\tTransforming %s..." % comp_fname category = "" if et.find("category"): category = et.find("category").text.strip() root = Element( "component", { "version": "1.0", "name": et.find("name").text.strip(), "description": et.find("description").text.strip(), "category": category }) tpcl_req = SubElement(root, "tpcl_requirements") tpcl_req.text = et.find("tpcl_requirements").text.strip() root.append(Comment("propertylist")) for prop in et.findall("property"): propelem = SubElement(root, "property", {"name": prop.find("name").text.strip()}) tpcl_cost = SubElement(propelem, "tpcl_cost") tpcl_cost.text = prop.find("tpcl_cost").text.strip() et = ElementTree(root) et.write(fpath, indent=True) elif version == "1.0": print "\tTransforming %s..." % comp_fname old_root = et.getroot() category = old_root.get("category") root = Element( "component", { "version": "1.1", "name": old_root.get("name"),
from elementtree.ElementTree import Element, dump note = Element("note") to = Element("to") to.text = "Tove" note.append(to) dump(note)
elem = Element(ns + 'langstring') elem.set('language', lang) elem.text = msg element.append(elem) #ugly way to find the right position for adding our stuff termIdBefore = [x for x in tree.findall('.//%stermIdentifier' % ns) if x.text == 'stress'][0] termBefore = [x for x in tree.getroot() if len(x) and x[0] == termIdBefore][0] term_position = [x for x in tree.getroot()].index(termBefore) # XML Creation new_root_element = Element(ns + 'term') termIdentifier = Element(ns + 'termIdentifier') termIdentifier.text = 'whp' new_root_element.append(termIdentifier) caption = Element(ns + 'caption') addLangs(caption, 'Workplace Health Promotion') new_root_element.append(caption) for key, value in tags.items(): new_element = Element(ns + 'term') termIdentifier = Element(ns + 'termIdentifier') termIdentifier.text = key new_element.append(termIdentifier) caption = Element(ns + 'caption') addLangs(caption, value) new_element.append(caption) new_root_element.append(new_element) tree.getroot().insert(term_position + 1, new_root_element) # you have to strip the ns0 and beautify it
class timing: def __init__(self, filename): self.filename = filename # we assume that the clock is the maximum length self.period = 40 self.height = 20 self.signalspacing = 10 self.xzero = 90 self.signalcnt = 0 self.cycles = 0 self.colors = ['powderblue', 'palegreen', 'lightpink', 'lightsalmon', 'lightgrey'] self.classes = {} self.svgelem = Element("svg") self.signalselem = Element("g") self.ypos = self.height + self.signalspacing def set_size(self): self.svgelem.attrib["width"] = str(self.xzero + int(self.cycles)*self.period + 2) self.svgelem.attrib['height'] = str(self.signalcnt * (self.height+ self.signalspacing) + self.signalspacing +2) def save(self): if self.filename == "": dump(self.svgelem) else: print "Creating ", self.filename ElementTree.ElementTree(self.svgelem).write(self.filename) def add_clock(self, name, datastr): sigelem = Element('g') # this is where we get the cycle count self.cycles = len(datastr.split()) clksig = signal(name, self.xzero, self.ypos, self.period, self.height) sigelem.append(clksig.draw_name()) for i in datastr.split(): sigelem.append(clksig.draw_clock()) self.ypos += self.signalspacing + self.height self.signalselem.append(sigelem) self.signalcnt += 1 def add_signal(self, name, datastr): sigelem = Element('g') sig = signal(name, self.xzero, self.ypos, self.period, self.height) sigelem.append(sig.draw_name()) for i in datastr.split(): if i == 'H': sigelem.append(sig.draw_high()) elif i == 'L': sigelem.append(sig.draw_low()) elif i == 'Z': sigelem.append(sig.draw_z()) elif i == '//': sigelem.append(sig.draw_split()) self.ypos += self.signalspacing + self.height self.signalselem.append(sigelem) self.signalcnt += 1 def add_bus(self, name, datastr, classstr): sigelem = Element('g') sig = signal(name, self.xzero, self.ypos, self.period, self.height) sigelem.append(sig.draw_name()) color = "white" data = datastr.split() if classstr != None: classes = classstr.split() for i in range(len(data)): cyccolor = color if len(classes) == 0: cl = 0 else: cl = classes[i] if self.classes.has_key(cl): cyccolor = self.classes[cl] else: cyccolor = self.colors.pop(0) self.classes[cl] = cyccolor if data[i] =='//': sigelem.append(sig.draw_split()) elif data[i] == 'Z': sigelem.append(sig.draw_z()) else: sigelem.append(sig.draw_bus(data[i], cyccolor)) self.ypos += self.signalspacing + self.height self.signalselem.append(sigelem) self.signalcnt += 1 def timinggrid(self): """ This function uses the signalcnt, cycles, period, height, and spacing to draw the light lines that will be the clock lines. """ gelem = Element("g") # create a group for i in range(int(self.cycles)): lelem = Element("line") lelem.attrib['x1'] = str(i*self.period + self.period/2.0 + self.xzero) lelem.attrib['y1'] = str(0); lelem.attrib['x2'] = str(i*self.period + self.period/2.0 + self.xzero) lelem.attrib['y2'] = str(self.signalcnt*(self.height + self.signalspacing) + self.signalspacing) lelem.attrib['stroke'] = "grey" lelem.attrib['stroke-width'] = "0.5" gelem.append(lelem) self.svgelem.append(gelem) self.svgelem.append(self.signalselem)
def CriarCredential(self, Aluno, Chave): """ Método que cria a credential do aluno para que o jenkins possa conectar no gitlab e fazer o git clone do projeto do aluno :param Aluno: Aluno é uma string contendo o email do aluno que será o nomer da credential :param Chave: Chave é uma string contendo a chave privada para a autenticação no gitlab. :returns: Esse método retorno o ID da credential criada para que ele possa ser vinculado na job. """ try: tree = parse("/var/lib/jenkins/credentials.xml") elem = tree.getroot() domain = elem.find("domainCredentialsMap") entry = domain.find("entry") Permissions = entry.find("java.util.concurrent.CopyOnWriteArrayList") chaveUsuario = Permissions.findall("com.cloudbees.jenkins.plugins.sshcredentials.impl.BasicSSHUserPrivateKey") for c in chaveUsuario: busca = c.findall("username") ids = c.findall("id") for b in busca: if Aluno in b.text: log.warning("[!] Credential deste aluno ja existe") return ids[busca.index(b)].text CXML = Element("com.cloudbees.jenkins.plugins.sshcredentials.impl.BasicSSHUserPrivateKey",plugin="[email protected]") NodeScope = Element("scope") NodeScope.text = "GLOBAL" CXML.append(NodeScope) NodeId = Element("id") NodeId.text = str(uuid.uuid1()) CXML.append(NodeId) NodeDesc = Element("description") CXML.append(NodeDesc) NodeUsername = Element("username") NodeUsername.text = Aluno CXML.append(NodeUsername) NodePassphrase = Element("passphrase") NodePassphrase.text = "ITkJ2nM+QRH/rnQJFb/h7kDKXnkpDW2TtMs5fstXnxQ=" CXML.append(NodePassphrase) NodePrivateKeySource = Element("privateKeySource",{"class":"com.cloudbees.jenkins.plugins.sshcredentials.impl.BasicSSHUserPrivateKey$DirectEntryPrivateKeySource"}) NodePrivateKey = Element("privateKey") NodePrivateKey.text = str(Chave) NodePrivateKeySource.append(NodePrivateKey) CXML.append(NodePrivateKeySource) #Identando XML XMLString = ElementTree.tostring(CXML) XMLIndentado = minidom.parseString(XMLString).toprettyxml() with open("/tmp/temp.xml","w") as f: f.write(XMLIndentado) f.close() #fim da identacao ArqXML = open("/tmp/temp.xml","r") XMLTemp = parse(ArqXML) Credential = XMLTemp.getroot() Permissions.append(Credential) tree.write("/var/lib/jenkins/credentials.xml") log.info("[+] Credential criada com sucesso") return NodeId.text except Exception as e: log.error("[-] Erro ao criar credential %s",e) return False
for comp_fname in os.listdir(comp_path): fpath = os.path.join(comp_path, comp_fname) et.parse(fpath) version = et.getroot().get("version") if not version: print "\tTransforming %s..." % comp_fname category = "" if et.find("category"): category = et.find("category").text.strip() root = Element("component", {"version": "1.0", "name": et.find("name").text.strip(), "description": et.find("description").text.strip(), "category": category}) tpcl_req = SubElement(root, "tpcl_requirements") tpcl_req.text = et.find("tpcl_requirements").text.strip() root.append(Comment("propertylist")) for prop in et.findall("property"): propelem = SubElement(root, "property", {"name": prop.find("name").text.strip()}) tpcl_cost = SubElement(propelem, "tpcl_cost") tpcl_cost.text = prop.find("tpcl_cost").text.strip() et = ElementTree(root) et.write(fpath, indent=True) elif version == "1.0": print "\tTransforming %s..." % comp_fname old_root = et.getroot() category = old_root.get("category") root = Element("component", {"version": "1.1", "name": old_root.get("name"), "description": old_root.get("description")})