def test_createSourceNodeFromExternalSourceWithDownStreamConnection(self):
        sourceControl = captureManager.createSourceControl()
        mediaSource = self.test_createSource()

        sinkControl = captureManager.createSinkControl()
        XMLstring = sinkControl.getCollectionOfSinks()
        root = ElementTree.fromstring(XMLstring)
        sinkFactories = ElementPath.findall(root, "SinkFactory")
        fileSinkFactoreGUID = ''
        asfContainerGUID = ''
        for sinkFactory in sinkFactories:
            if (sinkFactory.get('GUID') ==
                    '{D6E342E3-7DDD-4858-AB91-4253643864C2}'):
                fileSinkFactoreGUID = '{D6E342E3-7DDD-4858-AB91-4253643864C2}'
                for valuePart in ElementPath.findall(
                        sinkFactory, 'Value.ValueParts/ValuePart'):
                    if (valuePart.get('GUID') ==
                            '{A2A56DA1-EB84-460E-9F05-FEE51D8C81E3}'):
                        asfContainerGUID = '{A2A56DA1-EB84-460E-9F05-FEE51D8C81E3}'
        fileSinkFactory = SinkFactories.FileSinkFactory(
            sinkControl.createSinkFactory(asfContainerGUID,
                                          fileSinkFactoreGUID))

        indexOfStream = 0
        indexOfMediaType = 2

        outputMediaType = sourceControl.getSourceOutputMediaTypeFromMediaSource(
            mediaSource, indexOfStream, indexOfMediaType)
        aArrayPtrCompressedMediaTypes = []
        aArrayPtrCompressedMediaTypes.append(outputMediaType)
        outputNodes = fileSinkFactory.createOutputNodes(
            aArrayPtrCompressedMediaTypes, 'test.asf')

        sourceNode = sourceControl.createSourceNodeFromExternalSourceWithDownStreamConnection(
            mediaSource, indexOfStream, indexOfMediaType, outputNodes[0])
    def startCaptureSession(self):
        XMLstring = self.sinkControl.getCollectionOfSinks()
        root = ElementTree.fromstring(XMLstring)
        sinkFactories = ElementPath.findall(root, "SinkFactory")
        EVRSinkFactoreGUID = ''
        defaultContainerGUID = ''
        for sinkFactory in sinkFactories:
            if (sinkFactory.get('GUID') ==
                    '{2F34AF87-D349-45AA-A5F1-E4104D5C458E}'):
                EVRSinkFactoreGUID = '{2F34AF87-D349-45AA-A5F1-E4104D5C458E}'
                for valuePart in ElementPath.findall(
                        sinkFactory, 'Value.ValueParts/ValuePart'):
                    if (valuePart.get('GUID') ==
                            '{71FBA544-3A8E-4D6C-B322-98184BC8DCEA}'):
                        defaultContainerGUID = '{71FBA544-3A8E-4D6C-B322-98184BC8DCEA}'

        EVRSinkFactory = SinkFactories.EVRSinkFactory(
            self.sinkControl.createSinkFactory(defaultContainerGUID,
                                               EVRSinkFactoreGUID))

        indexOfStream = 0
        indexOfMediaType = int(self.prevSelectedMediaTypeIndex)
        outputNode = EVRSinkFactory.createOutputNode(self.frame.winfo_id())

        sourceNode = self.sourceControl.createSourceNodeWithDownStreamConnection(
            self.symbolicLink, indexOfStream, indexOfMediaType, outputNode)

        sources = []
        sources.append(sourceNode)
        self.session = self.sessionControl.createSession(sources)

        self.session.startSession(0, '{00000000-0000-0000-0000-000000000000}')
        self.controlBtnbox.subwidget('start').config(state='disabled')
        self.controlBtnbox.subwidget('stop').config(state='normal')
        self.controlBtnbox.subwidget('options').config(state='normal')
 def test_createSpreaderNode(self):
     fileSinkFactory = self.test_createFileSinkFactory()
     sourceControl = captureManager.createSourceControl()
     XMLstring = sourceControl.getCollectionOfSources()
     selfSources = ElementTree.fromstring(XMLstring)
     sources = ElementPath.findall(selfSources, "Source")
     symboliclink = ''
     for source in sources:
         state = False
         for attributes in ElementPath.findall(source, "Source.Attributes"):
             for attribute in ElementPath.findall(attributes, "Attribute"):
                 if (attribute.get(
                         'Name'
                 ) == 'MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE_VIDCAP_SYMBOLIC_LINK'
                     ):
                     symboliclink = attribute.find('SingleValue').get(
                         'Value')
     outputMediaType = sourceControl.getSourceOutputMediaType(
         symboliclink, 0, 0)
     aArrayPtrCompressedMediaTypes = []
     aArrayPtrCompressedMediaTypes.append(outputMediaType)
     aArrayPtrCompressedMediaTypes.append(outputMediaType)
     outputNodes = fileSinkFactory.createOutputNodes(
         aArrayPtrCompressedMediaTypes, 'test.asf')
     spreaderNodeFactory = self.test_createSpreaderNodeFactory()
     spreadNode = spreaderNodeFactory.createSpreaderNode(outputNodes)
Пример #4
0
 def search(self, **kwargs):
     k = (
          'groupId',
          'artifactId',
          'version',
          'extension',
          'sha1',
          'repositoryPath'
          )
     doc = dict()
     req_url = self.__buildURI(mountpoint='/service/local/artifact/maven/resolve', **kwargs)
     req = self.reqS.get(req_url)
     if req.status_code == 200:
         data = req.text
     else:
         return doc
     try:
         xml = ElementTree.XML(data)
         d = ElementPath.findall(xml, './/data')[0]
         for i in k:
             doc[i] = d.find(i).text
         doc['repository'] = kwargs['repository']
     except:
         pass
     return doc
Пример #5
0
 def iterfind(self, path, namespaces=None):
     # compile selector pattern
     if path[-1:] == "/":
         path = path + "*"  # implicit all (FIXME: keep this?)
     try:
         selector = ElementPath._cache[path]
     except KeyError:
         if len(ElementPath._cache) > 100:
             ElementPath._cache.clear()
         if path[:1] == "/":
             raise SyntaxError("cannot use absolute path on element")
         it = iter(ElementPath.xpath_tokenizer(path, namespaces))
         next_ = lambda: next(it)
         token = next_()
         selector = []
         while 1:
             try:
                 selector.append(ElementPath.ops[token[0]](next_,
                                                           token))
             except StopIteration:
                 raise SyntaxError("invalid path")
             try:
                 token = next_()
                 if token[0] == "/":
                     token = next_()
             except StopIteration:
                 break
         ElementPath._cache[path] = selector
     # execute selector pattern
     result = [self]
     context = self._SelectorContext(self)
     for select in selector:
         result = select(context, result)
     return result
Пример #6
0
    def _buildMetadata(self, xpath, metadata={}):
        parentXpath = xpath[:xpath.rfind("/")]
        childXpath = xpath[xpath.rfind("/") + 1:]

        if len(parentXpath) > 0:
            try:
                metadata[parentXpath].append(childXpath)
            except:
                metadata[parentXpath] = [childXpath]

        attributes = None
        next = iter(ElementPath.xpath_tokenizer(childXpath)).next

        while 1:
            try:
                token = next()
                if token[0] == "[":
                    attributes = self._transformAttr(next, token)
            except StopIteration:
                break

        if attributes is not None:
            childXpath = xpath[:xpath.rfind("[")]

        return childXpath, attributes
Пример #7
0
 def iterfind(self, path, namespaces=None):
     # compile selector pattern
     if path[-1:] == "/":
         path = path + "*" # implicit all (FIXME: keep this?)
     try:
         selector = ElementPath._cache[path]
     except KeyError:
         if len(ElementPath._cache) > 100:
             ElementPath._cache.clear()
         if path[:1] == "/":
             raise SyntaxError("cannot use absolute path on element")
         it = iter(ElementPath.xpath_tokenizer(path, namespaces))
         next_ = lambda: next(it)
         token = next_()
         selector = []
         while 1:
             try:
                 selector.append(ElementPath.ops[token[0]](next_, token))
             except StopIteration:
                 raise SyntaxError("invalid path")
             try:
                 token = next_()
                 if token[0] == "/":
                     token = next_()
             except StopIteration:
                 break
         ElementPath._cache[path] = selector
     # execute selector pattern
     result = [self]
     context = self._SelectorContext(self)
     for select in selector:
         result = select(context, result)
     return result
Пример #8
0
def pull_resource(path, wstype):
    response = soap('get', requestXml='''
<request operationName="get" locale="en">
<resourceDescriptor name="JRLogo" wsType="%(typ)s" uriString="%(path)s" isNew="false">
<label>JR logo</label>
<description>JR logo</description>
</resourceDescriptor>
</request>'''%dict(typ=wstype, path=path))
    res_tree = ET.fromstring(response.data.encode('utf-8'))
    res_desc = EP.find(res_tree, 'resourceDescriptor')
    # replace path and name as they are infered from git
    res_desc.attrib.pop('name', None)
    res_desc.attrib.pop('uriString', None)
    res_desc.attrib.pop('isNew', None)

    git = Popen(['git', 'hash-object', '-w', '--stdin'], stdin=PIPE, stdout=PIPE)
    new_blob = git.communicate(ET.tostring(res_desc))[0].strip()

    git_tree = []
    git_tree.append('100644 blob %s\t%s'%(new_blob, 'content'))
    for i, attach in enumerate(response.attachments):
        git = Popen(['git', 'hash-object', '-w', '--stdin'], stdin=PIPE, stdout=PIPE)
        new_blob = git.communicate(attach)[0].strip()
        git_tree.append('100644 blob %s\t%s'%(new_blob, 'data%d'%i))

    git_tree = '\n'.join(git_tree)
    git = Popen(['git', 'mktree'], stdin=PIPE, stdout=PIPE)
    new_tree = git.communicate(git_tree)[0].strip()

    return new_tree
    def _buildMetadata(self, xpath, metadata = {}):
        parentXpath = xpath[:xpath.rfind("/")]
        childXpath = xpath[xpath.rfind("/") + 1:]

        if len(parentXpath) > 0:
            try:
                metadata[parentXpath].append(childXpath)
            except:
                metadata[parentXpath] = [childXpath]

        attributes = None
        next = iter(ElementPath.xpath_tokenizer(childXpath)).next

        while 1:
                try:
                    token = next()
                    if token[0] == "[":
                        attributes = self._transformAttr(next, token)
                except StopIteration:
                    break

        if attributes is not None:
            childXpath = xpath[:xpath.rfind("[")]

        return childXpath, attributes
Пример #10
0
def pull_folder(path, typ='folder'):
    response = soap('list', requestXml='''
<request operationName="list" locale="en">
<resourceDescriptor name="" wsType="%(typ)s" uriString="%(path)s" isNew="false">
<label>null</label>
</resourceDescriptor>
</request>'''%dict(typ=typ, path=path))
    response = ET.fromstring(response.data.encode('utf-8'))
    res_list = EP.findall(response, 'resourceDescriptor')

    git_tree = []
    for res in res_list:
        res_type = res.attrib['wsType']
        res_uri = res.attrib['uriString']
        res_name = res_uri.rpartition('/')[2]
        if res_type == 'folder':
            blob = pull_folder(res_uri)
            if blob:
                git_tree.append('040000 tree %s\t%s'%(blob, res_name))
        else: #res_type in ('jdbc', 'img', 'reportUnit', 'dataType', 'inputControl'):
            blob = pull_resource(res_uri, res_type)
            git_tree.append('040000 tree %s\t%s'%(blob, res_name))
            print res_uri


    if git_tree:
        git_tree = '\n'.join(git_tree)
        git = Popen(['git', 'mktree'], stdin=PIPE, stdout=PIPE)
        new_blob = git.communicate(git_tree)[0].strip()

        return new_blob
    return
 def populateEncoderComboBox(self, selectedSourceIndex):
     if self.encoderComboBox.size() > 0:
         self.encoderComboBox.slistbox.listbox.delete(0, Tix.END)
     self.encoderCLSIDList = []
     self.encoderComboBox.config(state='normal')
     encodersXML = ElementTree.fromstring(
         self.encoderControl.getCollectionOfEncoders())
     groups = ElementPath.findall(encodersXML, "Group")
     for group in groups:
         if (group.get('GUID') == self.streamdescriptor.get('MajorTypeGUID')
             ):
             for encoderFactory in ElementPath.findall(
                     group, "EncoderFactory"):
                 self.encoderComboBox.insert(Tix.END,
                                             encoderFactory.get('Name'))
                 self.encoderCLSIDList.append(encoderFactory.get('CLSID'))
    def selectSource(self, event):
        selectedSourceIndex = self.sourceComboBox.subwidget_list[
            'slistbox'].subwidget_list['listbox'].curselection()
        if (self.prevSelectedSourceIndex != selectedSourceIndex[0]):
            self.prevSelectedSourceIndex = selectedSourceIndex[0]
            source = self.sourcesList[int(selectedSourceIndex[0])]
            for attributes in ElementPath.findall(source, "Source.Attributes"):
                for attribute in ElementPath.findall(attributes, "Attribute"):
                    if (attribute.get(
                            'Name'
                    ) == 'MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE_VIDCAP_SYMBOLIC_LINK'
                        ):
                        self.symbolicLink = attribute.find('SingleValue').get(
                            'Value')

            self.populateMediaTypeComboBox(int(selectedSourceIndex[0]))
    def test_createSourceNodeWithDownStreamConnection(self):
        sourceControl = captureManager.createSourceControl()
        XMLstring = sourceControl.getCollectionOfSources()
        selfSources = ElementTree.fromstring(XMLstring)
        sources = ElementPath.findall(selfSources, "Source")
        symboliclink = ''
        for source in sources:
            state = False
            for attributes in ElementPath.findall(source, "Source.Attributes"):
                for attribute in ElementPath.findall(attributes, "Attribute"):
                    if (attribute.get(
                            'Name'
                    ) == 'MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE_VIDCAP_SYMBOLIC_LINK'
                        ):
                        symboliclink = attribute.find('SingleValue').get(
                            'Value')
        sinkControl = captureManager.createSinkControl()
        XMLstring = sinkControl.getCollectionOfSinks()
        root = ElementTree.fromstring(XMLstring)
        sinkFactories = ElementPath.findall(root, "SinkFactory")
        fileSinkFactoreGUID = ''
        asfContainerGUID = ''
        for sinkFactory in sinkFactories:
            if (sinkFactory.get('GUID') ==
                    '{D6E342E3-7DDD-4858-AB91-4253643864C2}'):
                fileSinkFactoreGUID = '{D6E342E3-7DDD-4858-AB91-4253643864C2}'
                for valuePart in ElementPath.findall(
                        sinkFactory, 'Value.ValueParts/ValuePart'):
                    if (valuePart.get('GUID') ==
                            '{A2A56DA1-EB84-460E-9F05-FEE51D8C81E3}'):
                        asfContainerGUID = '{A2A56DA1-EB84-460E-9F05-FEE51D8C81E3}'
        fileSinkFactory = SinkFactories.FileSinkFactory(
            sinkControl.createSinkFactory(asfContainerGUID,
                                          fileSinkFactoreGUID))

        indexOfStream = 0
        indexOfMediaType = 2

        outputMediaType = sourceControl.getSourceOutputMediaType(
            symboliclink, indexOfStream, indexOfMediaType)
        aArrayPtrCompressedMediaTypes = []
        aArrayPtrCompressedMediaTypes.append(outputMediaType)
        outputNodes = fileSinkFactory.createOutputNodes(
            aArrayPtrCompressedMediaTypes, 'test.asf')

        sourceNode = sourceControl.createSourceNodeWithDownStreamConnection(
            symboliclink, indexOfStream, indexOfMediaType, outputNodes[0])
 def test_createSourceNode(self):
     sourceControl = captureManager.createSourceControl()
     XMLstring = sourceControl.getCollectionOfSources()
     selfSources = ElementTree.fromstring(XMLstring)
     sources = ElementPath.findall(selfSources, "Source")
     symboliclink = ''
     for source in sources:
         state = False
         for attributes in ElementPath.findall(source, "Source.Attributes"):
             for attribute in ElementPath.findall(attributes, "Attribute"):
                 if (attribute.get(
                         'Name'
                 ) == 'MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE_VIDCAP_SYMBOLIC_LINK'
                     ):
                     symboliclink = attribute.find('SingleValue').get(
                         'Value')
     sourceNode = sourceControl.createSourceNode(symboliclink, 0, 0)
Пример #15
0
 def __iter__(self):
     try:
         # same hack as above
         for child in ElementPath.findall(self._parent.getchildren(),
                                          self.tag):
             yield child
     except AttributeError:
         # this is the root element
         yield self
Пример #16
0
 def __iter__(self):
     try:
         # same hack as above
         for child in ElementPath.findall(self._parent.getchildren(),
                                          self.tag):
             yield child
     except AttributeError:
         # this is the root element
         yield self
Пример #17
0
 def __init__(self, widget, webCamControl):
     self.widget = widget
     self.webCamControl = webCamControl
     self.mainFrame = Tix.Frame(widget, bd=1, relief=Tix.RAISED)
     widget.wm_minsize(600, 400)
     camParametrs = self.webCamControl.getCamParametrs()
     parametrs = ElementTree.fromstring(camParametrs)
     groups = ElementPath.findall(parametrs, "Group")
     for group in groups:
         self.fillGroup(group)
Пример #18
0
 def process_xpath(content: "Element", xpath: str):
     with xpath_tokenizer_swap():
         return [
             stringify_xml(x, survey_nsmap_xpath)
             for x in EPath.iterfind(
                 elem=content,
                 path=xpath,
                 namespaces=survey_nsmap_xpath,
             )
         ]
 def test_createFileSinkFactory(self):
     sinkControl = captureManager.createSinkControl()
     XMLstring = sinkControl.getCollectionOfSinks()
     root = ElementTree.fromstring(XMLstring)
     sinkFactories = ElementPath.findall(root, "SinkFactory")
     fileSinkFactoreGUID = ''
     asfContainerGUID = ''
     for sinkFactory in sinkFactories:
         if (sinkFactory.get('GUID') ==
                 '{D6E342E3-7DDD-4858-AB91-4253643864C2}'):
             fileSinkFactoreGUID = '{D6E342E3-7DDD-4858-AB91-4253643864C2}'
             for valuePart in ElementPath.findall(
                     sinkFactory, 'Value.ValueParts/ValuePart'):
                 if (valuePart.get('GUID') ==
                         '{A2A56DA1-EB84-460E-9F05-FEE51D8C81E3}'):
                     asfContainerGUID = '{A2A56DA1-EB84-460E-9F05-FEE51D8C81E3}'
     fileSinkFactory = SinkFactories.FileSinkFactory(
         sinkControl.createSinkFactory(asfContainerGUID,
                                       fileSinkFactoreGUID))
     return fileSinkFactory
Пример #20
0
    def fillGroup(self, group):
        title = group.get('Title')
        labelframe = Tkinter.LabelFrame(self.widget, text=title)
        labelframe.pack(fill="both", expand="yes")
        parametrs = ElementPath.findall(group, "Parametr")

        index = 0
        for parametr in parametrs:
            WebCamProperty(labelframe, parametr, self.webCamControl, index / 5,
                           index % 5)
            index = index + 1
    def test_createSampleGrabberCallSinkFactory(self):
        sinkControl = captureManager.createSinkControl()
        XMLstring = sinkControl.getCollectionOfSinks()
        root = ElementTree.fromstring(XMLstring)
        sinkFactories = ElementPath.findall(root, "SinkFactory")
        SampleGrabberCallSinkFactoryGUID = ''
        defaultContainerGUID = ''
        for sinkFactory in sinkFactories:
            if (sinkFactory.get('GUID') ==
                    '{759D24FF-C5D6-4B65-8DDF-8A2B2BECDE39}'):
                SampleGrabberCallSinkFactoryGUID = '{759D24FF-C5D6-4B65-8DDF-8A2B2BECDE39}'
                for valuePart in ElementPath.findall(
                        sinkFactory, 'Value.ValueParts/ValuePart'):
                    if (valuePart.get('GUID') ==
                            '{C1864678-66C7-48EA-8ED4-48EF37054990}'):
                        defaultContainerGUID = '{C1864678-66C7-48EA-8ED4-48EF37054990}'

        SampleGrabberCallSinkFactory = SinkFactories.SampleGrabberCallSinkFactory(
            sinkControl.createSinkFactory(defaultContainerGUID,
                                          SampleGrabberCallSinkFactoryGUID))
        return SampleGrabberCallSinkFactory
Пример #22
0
    def test_predicate(self):
        """Test predicate addition
        """
        element_test = ET.Element("test")
        element_temp = ET.Element("test")
        element_temp.text = "Hey"
        element_temp.set("val", "8")
        ET.SubElement(element_temp, "ins")

        token_iter = EP.xpath_tokenizer("@val=8]")
        xmlconfigparse.add_predicate(token_iter, element_test)
        token_iter = EP.xpath_tokenizer("text()=Hey]")
        xmlconfigparse.add_predicate(token_iter, element_test)
        token_iter = EP.xpath_tokenizer("ins/]")
        xmlconfigparse.add_predicate(token_iter, element_test)

        element_temp_string = ET.tostring(element_temp)
        element_test_string = ET.tostring(element_test)
        self.assertEqual(
            element_test_string, element_temp_string, msg="Unexpected string returned"
        )
    def populateOutputContainerTypeComboBox(self):
        if self.outputContainerTypeComboBox.size() > 0:
            self.outputContainerTypeComboBox.slistbox.listbox.delete(
                0, Tix.END)

        self.outputContainerTypeComboBox.config(state='normal')
        self.outputContainerTypeGUIDList = []
        self.outputContainerTypeList = []
        XMLstring = self.sinkControl.getCollectionOfSinks()
        root = ElementTree.fromstring(XMLstring)
        sinkFactories = ElementPath.findall(root, "SinkFactory")
        for sinkFactory in sinkFactories:
            if (sinkFactory.get('GUID') ==
                    '{D6E342E3-7DDD-4858-AB91-4253643864C2}'):
                for valuePart in ElementPath.findall(
                        sinkFactory, 'Value.ValueParts/ValuePart'):
                    self.outputContainerTypeComboBox.insert(
                        Tix.END, valuePart.get('Value'))
                    self.outputContainerTypeGUIDList.append(
                        valuePart.get('GUID'))
                    self.outputContainerTypeList.append(valuePart.get('Value'))
    def test_createEVRSinkFactory(self):
        sinkControl = captureManager.createSinkControl()
        XMLstring = sinkControl.getCollectionOfSinks()
        #print XMLstring
        root = ElementTree.fromstring(XMLstring)
        sinkFactories = ElementPath.findall(root, "SinkFactory")
        EVRSinkFactoreGUID = ''
        defaultContainerGUID = ''
        for sinkFactory in sinkFactories:
            if (sinkFactory.get('GUID') ==
                    '{2F34AF87-D349-45AA-A5F1-E4104D5C458E}'):
                EVRSinkFactoreGUID = '{2F34AF87-D349-45AA-A5F1-E4104D5C458E}'
                for valuePart in ElementPath.findall(
                        sinkFactory, 'Value.ValueParts/ValuePart'):
                    if (valuePart.get('GUID') ==
                            '{71FBA544-3A8E-4D6C-B322-98184BC8DCEA}'):
                        defaultContainerGUID = '{71FBA544-3A8E-4D6C-B322-98184BC8DCEA}'

        EVRSinkFactory = SinkFactories.EVRSinkFactory(
            sinkControl.createSinkFactory(defaultContainerGUID,
                                          EVRSinkFactoreGUID))
        return EVRSinkFactory
Пример #25
0
    def downloadArtifact(self):
        url = self.get_artifact_url()
        data = urllib2.urlopen(url).read()
        doc = ElementTree.XML(data)
        elements = ElementPath.findall(doc, ".//artifact")
        artifacts = []
        
        #create a list of artifacts
        for x in elements:
            artifacts.append((x.find("resourceURI").text,
                              x.find("groupId").text, 
                              x.find("artifactId").text, 
                              x.find("version").text, 
                              x.find("packaging").text,
                              x.find("extension").text,
                              x.find("repoId").text, 
                              x.find("contextId").text, 
                              x.find("pomLink").text, 
                              x.find("artifactLink").text))
            

        #Filter on snapshots or releases
        artifacts = [artifact for artifact in artifacts if artifact[6].lower() == self.repository.lower()]
        #Filter on group
        artifacts = [artifact for artifact in artifacts if artifact[1].lower() == self.group.lower()]
        #Filter on artifact name
        artifacts = [artifact for artifact in artifacts if artifact[2].lower() == self.artifact.lower()]
        #print artifacts
        artifact_name=""
        if artifacts:
            #Get the last artifact in the list
            artifact = artifacts[-1]
            
            artifact_url = artifact[9]
            artifact_name = artifact[0].split('/')[-1]
            dlfile = self.download(artifact_url, artifact_name)
            if "Error Not Found 404" in dlfile:
                print("Downloading from: "+artifact[0])
                #Try the download again using the undirected link
                dlfile = self.download(artifact[0], artifact_name)

            print("Downloaded: "+dlfile)
            file_hashes = self.hashfile(dlfile)
            print("SHA1: "+file_hashes[0])
            print("MD5 : "+file_hashes[1])
            
                    
        print("-"*40)

        return artifact_name 
Пример #26
0
    def test_elementinset(self):
        """Test method insert subelements
        """
        element_test = ET.Element("test")
        element_temp = ET.Element("test")
        new_temp = ET.SubElement(element_temp, "new")
        ET.SubElement(new_temp, "insert")
        token_iter = EP.xpath_tokenizer("new/insert")
        xmlconfigparse.elementinsert(token_iter, element_test)

        element_temp_string = ET.tostring(element_temp)
        element_test_string = ET.tostring(element_test)
        self.assertEqual(
            element_test_string, element_temp_string, msg="Unexpected string returned"
        )
Пример #27
0
 def getversions(self, **kwargs):
     versions = ()
     kwargs['version'] = 'any'
     req_url = self.__buildURI(mountpoint='/service/local/lucene/search', **kwargs)
     with requests_cache.disabled():
         req = self.reqS.get(req_url)
     if req.status_code == 200:
         data = req.text
     else:
         return versions
     try:
         xml = ElementTree.XML(data)
         for item in ElementPath.findall(xml, './/artifact'):
             if item.find('artifactId').text == kwargs['artifact_id']:
                 versions = versions + (item.find('version').text,)
     except:
         pass
     return versions
    def populateEncoderModeComboBox(self, encoderCLSID):
        if self.encoderModeComboBox.size() > 0:
            self.encoderModeComboBox.slistbox.listbox.delete(0, Tix.END)

        self.encoderModeComboBox.config(state='normal')
        self.encoderModelist = []
        self.encoderModeGUIDlist = []
        selectedMediaTypeIndex = self.mediaTypeComboBox.subwidget_list[
            'slistbox'].subwidget_list['listbox'].curselection()
        outputMediaType = self.sourceControl.getSourceOutputMediaType(
            self.symbolicLink, 0, int(selectedMediaTypeIndex[0]))

        encoderOutputMedaiTypesXml = ElementTree.fromstring(
            self.encoderControl.getMediaTypeCollectionOfEncoder(
                outputMediaType, encoderCLSID))
        groups = ElementPath.findall(encoderOutputMedaiTypesXml, "Group")
        for group in groups:
            self.encoderModeComboBox.insert(Tix.END, group.get('Title'))
            self.encoderModelist.append(group)
            self.encoderModeGUIDlist.append(group.get('GUID'))
Пример #29
0
def xmlinsert(xpath, xmlfile, tag=".", findall=False):
    """Inserts elements from an xpath

    refs: xml.etree.ElementPath
          https://github.com/python/cpython/blob/3.7/Lib/xml/etree/ElementPath.py

    Args:
        xpath (str): xml elements separated by back slash
            (no whitespace outside of attributes)
        xmlfile (str): path to xml file; created if it doesn't exist
        tag (str): xml element to serve as parent (/ or . = root)
        findall (bool): If true finds all matching times matching tag
            and inserts xml elements from xpaths after deepest member
    Returns:
        str: location of updated xml file

    Notes:
        xpath (str): expects paths which only descend.  And supports
            the following symbols in xpath /()[]@= excludes (//, ..)
            ex. a[bar=/hello/world]/be[text()="there"]/can[@nope=there]/day

        tag (str): used by implementation of Elementree's iterfind function
            so see xml.etree.elementree for limitations.
    """
    # import xml and convert to element
    tree = ET.parse(xmlfile)
    root = tree.getroot()
    # no absolute paths
    if xpath[0] == "/":
        raise SyntaxError("Can't create another root directory in an xml file")
    token_iter = EP.xpath_tokenizer(xpath)
    # check recursive
    if findall:
        for element in root.iterfind(tag):
            elementinsert(token_iter, element)
    else:
        # if tag defined root replaced
        elementinsert(token_iter, root.find(tag))
    tree.write(xmlfile)
    return xmlfile
    def ExportXML(self, filename = None):
        """ Build element tree from xpaths """

        # Tree root node
        root = None

        #Map to store xpath and ElementXpath
        self.mapparentelem = {}

        ''' Select all rows of db to export '''
        for xpath in self.Iterators('/'):
            #Is attribute xpath? /a/b/c@name => attr name
            attr_xpath = False 

            try:
              value = str(self.Read(xpath))
            except SystemError, e:
              print "Cannot read [%s], error %s" % (xpath,str(e))
              continue
            next = iter(ElementPath.xpath_tokenizer(xpath)).next

            #For each leaf node on xpath
            current_elemment = root

            #parent xpath
            parent_xpath = None

            #current xpath token
            current_xpath = None

            while 1:
                try:
                    token = next()
                    if token[0] == "/":
                        token = next()

                        #Ignore attribue element (xpath=//sg/@name)
                        if token[0] == "@":
                            attr_xpath = True
                            continue

                        index = xpath.rfind("/%s" %token[1])
                        if index >= 0:
                            parent_xpath = "%s" %(xpath[:index])

                            #Get xpath assume suffix is leaf
                            next_index = xpath.find("/", len(parent_xpath) + 1)
                            if next_index>0:
                                current_xpath = xpath[0:next_index]
                            else:
                                #Last leaf
                                current_xpath = xpath

                            if root is None:
                                root = ET.Element(key_to_xml(token[1]))
                                current_elemment = root
                                self.mapparentelem["/%s" %token[1]] = current_elemment
                            else:
                                current_elemment = self._buildNode(current_xpath)
                    elif token[0] == "[":
                        attributes = self._transformAttr(next, token)
                        if len(attributes) > 0:
                            current_elemment.attrib = attributes

                except StopIteration:
                    break

            if attr_xpath == False:
                current_elemment.text = value
Пример #31
0
 def __getattr__(self, name):
     # the following depends on ElementPath internals, but should be fine
     result = ElementPath.find(self.getchildren(), self._namespace + name)
     if result is None:
         raise AttributeError('No such element: {}'.format(name))
     return result
Пример #32
0
    def ExportXML(self, filename=None):
        """ Build element tree from xpaths """

        # Tree root node
        root = None

        #Map to store xpath and ElementXpath
        self.mapparentelem = {}
        ''' Select all rows of db to export '''
        for xpath in self.Iterators('/'):
            #Is attribute xpath? /a/b/c@name => attr name
            attr_xpath = False

            try:
                value = str(self.Read(xpath))
            except SystemError, e:
                print "Cannot read [%s], error %s" % (xpath, str(e))
                continue
            next = iter(ElementPath.xpath_tokenizer(xpath)).next

            #For each leaf node on xpath
            current_elemment = root

            #parent xpath
            parent_xpath = None

            #current xpath token
            current_xpath = None

            while 1:
                try:
                    token = next()
                    if token[0] == "/":
                        token = next()

                        #Ignore attribue element (xpath=//sg/@name)
                        if token[0] == "@":
                            attr_xpath = True
                            continue

                        index = xpath.rfind("/%s" % token[1])
                        if index >= 0:
                            parent_xpath = "%s" % (xpath[:index])

                            #Get xpath assume suffix is leaf
                            next_index = xpath.find("/", len(parent_xpath) + 1)
                            if next_index > 0:
                                current_xpath = xpath[0:next_index]
                            else:
                                #Last leaf
                                current_xpath = xpath

                            if root is None:
                                root = ET.Element(key_to_xml(token[1]))
                                current_elemment = root
                                self.mapparentelem["/%s" %
                                                   token[1]] = current_elemment
                            else:
                                current_elemment = self._buildNode(
                                    current_xpath)
                    elif token[0] == "[":
                        attributes = self._transformAttr(next, token)
                        if len(attributes) > 0:
                            current_elemment.attrib = attributes

                except StopIteration:
                    break

            if attr_xpath == False:
                current_elemment.text = value
    def __init__(self, widget, captureManager):
        self.captureManager = captureManager
        self.sourcesList = []
        self.prevSelectedSourceIndex = -1
        self.prevSelectedMediaTypeIndex = -1
        self.sourceComboBox = Tix.ComboBox(widget,
                                           label="Source: ",
                                           command=self.selectSource)
        self.sourceComboBox.pack(side=Tix.TOP, fill=Tix.X)
        self.sourceControl = self.captureManager.createSourceControl()
        self.sinkControl = self.captureManager.createSinkControl()
        self.sessionControl = self.captureManager.createSessionControl()
        self.session = -1
        xmlstring = self.sourceControl.getCollectionOfSources()
        selfSources = ElementTree.fromstring(xmlstring)
        self.sources = ElementPath.findall(selfSources, "Source")
        for source in self.sources:
            friendlyname = ''
            state = False
            for attributes in ElementPath.findall(source, "Source.Attributes"):
                for attribute in ElementPath.findall(attributes, "Attribute"):
                    if (attribute.get('Name') ==
                            'MF_DEVSOURCE_ATTRIBUTE_FRIENDLY_NAME'):
                        friendlyname = attribute.find('SingleValue').get(
                            'Value')
                    if (attribute.get('Name') ==
                            'MF_DEVSOURCE_ATTRIBUTE_MEDIA_TYPE'):
                        parts = attribute.find('Value.ValueParts').findall(
                            "ValuePart")
                        for part in parts:
                            if (part.get('Value') == 'MFMediaType_Video'):
                                state = True

            if (state):
                self.sourceComboBox.insert(Tix.END, friendlyname)
                self.sourcesList.append(source)
        self.mediaTypeComboBox = Tix.ComboBox(widget,
                                              label="MediaTypes: ",
                                              state='disabled',
                                              command=self.selectMediaType)
        self.mediaTypeComboBox.pack(side=Tix.TOP, fill=Tix.X)
        self.controlBtnbox = Tix.ButtonBox(widget, orientation=Tix.HORIZONTAL)
        self.startBtn = self.controlBtnbox.add(
            'start',
            text='Start',
            underline=0,
            width=6,
            state='disabled',
            command=lambda widget=widget: self.startCaptureSession())
        self.optionsBtn = self.controlBtnbox.add(
            'options',
            text='Options',
            underline=0,
            width=6,
            state='disabled',
            command=lambda widget=widget: self.options())
        self.stopBtn = self.controlBtnbox.add(
            'stop',
            text='Stop',
            underline=0,
            width=6,
            state='disabled',
            command=lambda widget=widget: self.stopCaptureSession())
        self.controlBtnbox.pack(side=Tix.TOP, fill=Tix.X)

        self.frame = Tkinter.Frame(widget, relief=RIDGE, borderwidth=2)
        self.frame.pack(fill=BOTH, expand=1)
Пример #34
0
 def __getattr__(self, name):
     # the following depends on ElementPath internals, but should be fine
     result = ElementPath.find(self.getchildren(), self._namespace + name)
     if result is None:
         raise AttributeError('No such element: {}'.format(name))
     return result
 def __init__(self, widget, captureManager):
     self.captureManager = captureManager
     self.sourcesList = []
     self.prevSelectedSourceIndex = -1
     self.prevSelectedMediaTypeIndex = -1
     self.prevSelectedEncoderIndex = -1
     self.streamdescriptor = -1
     self.prevSelectedEncoderModeIndex = -1
     self.prevSelectedOutputContainerTypeIndex = -1
     self.sourceComboBox = Tix.ComboBox(widget,
                                        label="Source: ",
                                        command=self.selectSource)
     self.sourceComboBox.pack(side=Tix.TOP, fill=Tix.X)
     self.sourceControl = self.captureManager.createSourceControl()
     self.sinkControl = self.captureManager.createSinkControl()
     self.encoderControl = self.captureManager.createEncoderControl()
     self.sessionControl = self.captureManager.createSessionControl()
     self.session = None
     self.encoderCLSIDList = []
     self.selectedEncoderCLSID = -1
     selfSources = ElementTree.fromstring(
         self.sourceControl.getCollectionOfSources())
     self.sources = ElementPath.findall(selfSources, "Source")
     for source in self.sources:
         friendlyname = ''
         for attributes in ElementPath.findall(source, "Source.Attributes"):
             for attribute in ElementPath.findall(attributes, "Attribute"):
                 if (attribute.get('Name') ==
                         'MF_DEVSOURCE_ATTRIBUTE_FRIENDLY_NAME'):
                     friendlyname = attribute.find('SingleValue').get(
                         'Value')
         self.sourceComboBox.insert(Tix.END, friendlyname)
         self.sourcesList.append(source)
     self.mediaTypeComboBox = Tix.ComboBox(widget,
                                           label="MediaType: ",
                                           state='disabled',
                                           command=self.selectMediaType)
     self.mediaTypeComboBox.pack(side=Tix.TOP, fill=Tix.X)
     self.encoderComboBox = Tix.ComboBox(widget,
                                         label="Encoder: ",
                                         state='disabled',
                                         command=self.selectEncoder)
     self.encoderComboBox.pack(side=Tix.TOP, fill=Tix.X)
     self.encoderModeComboBox = Tix.ComboBox(widget,
                                             label="EncoderMode: ",
                                             state='disabled',
                                             command=self.selectEncoderMode)
     self.encoderModeComboBox.pack(side=Tix.TOP, fill=Tix.X)
     self.encoderOutputMediaTypeComboBox = Tix.ComboBox(
         widget,
         label="EncoderOutputMediaType: ",
         state='disabled',
         command=self.selectEncoderOutputMediaType)
     self.encoderOutputMediaTypeComboBox.pack(side=Tix.TOP, fill=Tix.X)
     self.outputSinkTypeComboBox = Tix.ComboBox(
         widget,
         label="OutputSinkType: ",
         state='disabled',
         command=self.selectOutputSinkType)
     self.outputSinkTypeComboBox.pack(side=Tix.TOP, fill=Tix.X)
     self.outputContainerTypeComboBox = Tix.ComboBox(
         widget,
         label="OutputContainerType: ",
         state='disabled',
         command=self.selectOutputContainerType)
     self.outputContainerTypeComboBox.pack(side=Tix.TOP, fill=Tix.X)
     self.optionsBtn = Tkinter.Button(widget,
                                      text='Options',
                                      state='disabled',
                                      command=self.showOptions)
     self.optionsBtn.pack(side=Tix.TOP, fill=Tix.X)
     self.sessionBtn = Tkinter.Button(widget,
                                      text='Session',
                                      state='disabled',
                                      command=self.initSession)
     self.sessionBtn.pack(side=Tix.TOP, fill=Tix.X)
Пример #36
0
    else:
        print 'Error status code: ', status
    return tree

try:  
    result = getXml("http://localhost:8080/PracticalCaseWS/WSCatalogRest/listAllCategories");
    exitall = 1
    while exitall>0:
        n=1  
        menu =[]      
        print("");
        print("          P E T S    S H O P");
        print("          Practical Case Study based on Rest Web Service and Python Client");
        print("          You can list all the pets or list them by category.");
        print("");
        for elem in ElementPath.findall(result, ".//category"):
            print "          ",n," - ",elem.find('name').text , " "
            menu.append(elem.find('name').text)
            n +=1
        print("           0 - Exit "); 
        c1 = raw_input("           Choose a number: ")                                            
        try: 
            c = int(c1)
            if c==0:
                exitall = 0
            else:
                if c>0 and c<n:
                    pet = []
                    if menu[c-1].rstrip() =="ALL PETS":
                        doc = getXml("http://localhost:8080/PracticalCaseWS/WSCatalogRest/listAllPets");                                                
                    else: