Identify a file object as XML (any format)
8403
def is_xml(origin, filepath, fileobj, *args, **kwargs):
    
    # pylint: disable=unused-argument
    if fileobj is not None:
        loc = fileobj.tell()
        fileobj.seek(0)
        try:
            sig = fileobj.read(5).lower()
            return sig == XML_SIGNATURE
        finally:
            fileobj.seek(loc)
    elif filepath is not None:
        return filepath.endswith(('.xml', '.xml.gz'))
876087
def fromxml(node):
        """"""
        if not isinstance(node,ElementTree._Element): #pylint: disable=protected-access
            node = parsexmlstring(node)
        assert node.tag.lower() == 'outputtemplate'

        template_id = node.attrib['id']
        dataformat = node.attrib['format']
        label = node.attrib['label']
        kwargs = {}
        if 'filename' in node.attrib:
            kwargs['filename'] = node.attrib['filename']
        if 'extension' in node.attrib:
            kwargs['extension'] = node.attrib['extension']
        if 'unique' in node.attrib:
            kwargs['unique'] = node.attrib['unique'].lower() == 'yes' or node.attrib['unique'].lower() == 'true' or node.attrib['unique'].lower() == '1'
        if 'parent' in node.attrib:
            kwargs['parent'] = node.attrib['parent']

        #find formatclass
        formatcls = None
        for C in CUSTOM_FORMATS: #CUSTOM_FORMATS will be injected by clamservice.py
            if C.__name__ == dataformat:
                formatcls = C
                break
        if formatcls is None:
            if dataformat in vars(clam.common.formats):
                formatcls = vars(clam.common.formats)[dataformat]
            else:
                raise Exception("Specified format not defined! (" + dataformat + ")")

        args = []
        for subnode in node:
            if subnode.tag == 'parametercondition':
                args.append(ParameterCondition.fromxml(subnode))
            elif subnode.tag == 'converter':
                pass #MAYBE TODO: Reading converters from XML is not implemented (and not necessary at this stage)
            elif subnode.tag == 'viewer':
                pass #MAYBE TODO: Reading viewers from XML is not implemented (and not necessary at this stage)
            else:
                args.append(AbstractMetaField.fromxml(subnode))

        return OutputTemplate(template_id,formatcls,label, *args, **kwargs)
516090
def read_xml(filename):
    
    parser = et.XMLParser(remove_blank_text=True)
    isfile=False
    try:
        isfile = os.path.exists(filename)
    except ValueError as e:
        if 'path too long for Windows' in str(e):
            pass
        else:
            raise
    try:
        if isfile:
            return et.parse(filename, parser)
        else:
            r = et.fromstring(filename, parser)
            return r.getroottree()
    except IOError:
        log.exception('unable to open file [[}]'.format(filename))
    except et.XMLSyntaxError:
        log.exception('unable to parse XML [{}]'.format(filename))
        return None
    return None
18526
public static void objectToXML(Object object, String fileName) throws FileNotFoundException {
		FileOutputStream fo = new FileOutputStream(fileName);
		XMLEncoder encoder = new XMLEncoder(fo);
		encoder.writeObject(object);
		encoder.close();
	}
860684
def disk_xml(identifier, pool_xml, base_volume_xml, cow):
    
    pool = etree.fromstring(pool_xml)
    base_volume = etree.fromstring(base_volume_xml)
    pool_path = pool.find('.//path').text
    base_path = base_volume.find('.//target/path').text
    target_path = os.path.join(pool_path, '%s.qcow2' % identifier)
    volume_xml = VOLUME_DEFAULT_CONFIG.format(identifier, target_path)
    volume = etree.fromstring(volume_xml)
    base_volume_capacity = base_volume.find(".//capacity")

    volume.append(base_volume_capacity)

    if cow:
        backing_xml = BACKING_STORE_DEFAULT_CONFIG.format(base_path)
        backing_store = etree.fromstring(backing_xml)
        volume.append(backing_store)

    return etree.tostring(volume).decode('utf-8')
1359777
def getXMLDescription(cliExecutable, **kwargs):
    """"""

    command = [cliExecutable, '--xml']
    
    stdout, stdoutFilename = tempfile.mkstemp('.stdout')
    stderr, stderrFilename = tempfile.mkstemp('.stderr')
    try:
        p = popenCLIExecutable(command, stdout = stdout, stderr = stderr, **kwargs)
        ec = p.wait()
        with open(stderrFilename) as f:
            for line in f:
                logger.warning('%s: %s' % (os.path.basename(cliExecutable), line[:-1]))
        if ec:
            raise RuntimeError("Calling %s failed (exit code %d)" % (cliExecutable, ec))
        with open(stdoutFilename) as f:
            return ET.parse(f)
    finally:
        os.close(stdout)
        os.close(stderr)
        os.unlink(stdoutFilename)
        os.unlink(stderrFilename)
811634
def load(self, filename):
        
        #if LXE and self.mode != Mode.XPATH:
        #    #workaround for xml:id problem (disabled)
        #    #f = open(filename)
        #    #s = f.read().replace(' xml:id=', ' id=')
        #    #f.close()
        #    self.tree = ElementTree.parse(filename)
        #else:
        self.tree = xmltreefromfile(filename)
        self.parsexml(self.tree.getroot())
        if self.mode != Mode.XPATH:
            #XML Tree is now obsolete (only needed when partially loaded for xpath queries)
            self.tree = None
1220719
def fileobj_name(fileobj):
    

    value = getattr(fileobj, "name", u"")
    if not isinstance(value, (text_type, bytes)):
        value = text_type(value)
    return value
556786
def _get_content_type(self, filename):
        
        mntype = mimetypes.guess_type(filename)[0]
        filename, fileExtension = os.path.splitext(filename)
        if mntype is None and\
            fileExtension.lower() == ".csv":
            mntype = "text/csv"
        elif mntype is None and \
            fileExtension.lower() == ".sd":
            mntype = "File/sd"
        elif mntype is None:
            #mntype = 'application/octet-stream'
            mntype= "File/%s" % fileExtension.replace('.', '')
        return mntype
142410
def load(filename):
        
        # parse a zipped file
        if zipfile.is_zipfile(filename):
            zfile = zipfile.ZipFile(filename, 'r')
            try:
                xml = ElementTree.fromstring(zfile.read('scaffold.xml'))
            except StandardError:
                logger.exception('Failed to load scaffold: {0}'.format(filename))
                zfile.close()
                return None
            zfile.close()

        # parse a standard xml file
        else:
            try:
                xml = ElementTree.parse(filename).getroot()
            except StandardError:
                logger.exception('Failed to load scaffold: {0}'.format(filename))
                return None

        # generate a scaffold
        scaffold = Scaffold()
        scaffold.setSource(filename)
        scaffold.setName(xml.get('name', 'Missing'))
        scaffold.setGroup(xml.get('group', 'Default'))
        scaffold.setLanguage(xml.get('lang', 'Python'))
        scaffold.setIcon(xml.get('icon', ''))

        # define properties
        xprops = xml.find('properties')
        if xprops is not None:
            for xprop in xprops:
                scaffold.addProperty(Property.fromXml(xprop))

        return scaffold
1211599
def readerForFile(filename, encoding, options):
    
    ret = libxml2mod.xmlReaderForFile(filename, encoding, options)
    if ret is None:raise treeError('xmlReaderForFile() failed')
    return xmlTextReader(_obj=ret)
476709
def xml(self, indent = ""):
        """"""
        xml = indent + "<OutputTemplate id=\"" + self.id + "\" format=\"" + self.formatclass.__name__ + "\"" + " label=\"" + self.label + "\""
        if self.formatclass.mimetype:
            xml +=" mimetype=\""+self.formatclass.mimetype+"\""
        if self.formatclass.schema:
            xml +=" schema=\""+clam.common.util.xmlescape(self.formatclass.schema)+"\""
        if self.filename:
            xml +=" filename=\""+clam.common.util.xmlescape(self.filename)+"\""
        if self.extension:
            xml +=" extension=\""+clam.common.util.xmlescape(self.extension)+"\""
        if self.parent:
            xml +=" parent=\""+clam.common.util.xmlescape(self.parent)+"\""
        if self.unique:
            xml +=" unique=\"yes\""
        else:
            xml +=" unique=\"no\""
        xml += ">\n"
        for metafield in self.metafields:
            xml += metafield.xml(indent + "    ") + "\n"

        xml += indent + "</OutputTemplate>"
        return xml
760886
def __get_file(self, file):
        
        file_object = None
        if file['name'] in request.files:
            file_object = request.files[file['name']]
            clean_filename = secure_filename(file_object.filename)
            if clean_filename == '':
                return file_object
            if file_object and self.__allowed_extension(
                    clean_filename, file['extensions']):
                return file_object
        elif file['name'] not in request.files and file['required']:
            return file_object
        return file_object
1303064
def from_xml(cls, xml_bytes):
        
        root = XML(xml_bytes)
        return cls(root.findtext('Bucket'),
                   root.findtext('Key'),
                   root.findtext('UploadId'))
158396
private Document toXML(Collection<ArchiveEntry> files) throws Exception
    {
        Document doc = new DOMDocument();

        Element packageElement = new DOMElement("package");
        doc.setRootElement(packageElement);

        Element infoElement = new DOMElement("infos");
        packageElement.add(infoElement);
        addInfoElements(infoElement);

        Element filesElement = new DOMElement(FILES_TAG);
        packageElement.add(filesElement);
        addFileElements(files, filesElement);

        return doc;
    }
55144
def determine_file_extension_based_on_format(format_specifier):
	
	if format_specifier == FMT_INI:
		return 'ini'
	if format_specifier == FMT_DELIMITED:
		return ''
	if format_specifier == FMT_XML:
		return 'xml'
	if format_specifier == FMT_JSON:
		return 'json'
	if format_specifier == FMT_YAML:
		return 'yml'
	raise ValueError('invalid format specifier: {}'.format(format_specifier))
794456
def resource_as_xml(self, resource):
        
        e = self.resource_etree_element(resource)
        if (sys.version_info >= (3, 0)):
            # python3.x
            return(tostring(e, encoding='unicode', method='xml'))
        elif (sys.version_info >= (2, 7)):
            s = tostring(e, encoding='UTF-8', method='xml')
        else:
            # must not specify method='xml' in python2.6
            s = tostring(e, encoding='UTF-8')
        # Chop off XML declaration that is added in 2.x... sigh
        return(s.replace("<?xml version='1.0' encoding='UTF-8'?>\n", ''))