コード例 #1
0
ファイル: drv_javasax.py プロジェクト: jythontools/jython
def create_java_parser(jdriver=None):
    try:
        if jdriver:
            return XMLReaderFactory.createXMLReader(jdriver)
        elif jaxp:
            return factory.newSAXParser().getXMLReader()
        else:
            return XMLReaderFactory.createXMLReader()
    except ParserConfigurationException, e:
        raise _exceptions.SAXReaderNotAvailable(e.getMessage())
コード例 #2
0
def create_java_parser(jdriver=None):
    try:
        if jdriver:
            return XMLReaderFactory.createXMLReader(jdriver)
        elif jaxp:
            return factory.newSAXParser().getXMLReader()
        else:
            return XMLReaderFactory.createXMLReader()
    except ParserConfigurationException, e:
        raise _exceptions.SAXReaderNotAvailable(e.getMessage())
コード例 #3
0
def mainproc():
    u'''Функция для склейки карточки с блоками правил'''
    try:
        rootPath = AppInfoSingleton.getAppInfo().getCurUserData().getPath(
        ) + '/xforms/'
    except:
        rootPath = 'E:/Projects/celesta/ssmmd/userscore/ssmmd/xforms/file/'

    templatePath = rootPath + add  #путь к карточке, в которую необходимо вставить праила
    rulePath = rootPath + 'ruleTemplate.xml'  #путь к блоку с правилами
    bindPath = rootPath + 'bindTemplate.xml'  #путь к блоку с биндами для правил

    stringWriter = StringWriter()
    xmlWriter = XMLOutputFactory.newInstance().createXMLStreamWriter(
        stringWriter)

    parser = XMLReaderFactory.createXMLReader()
    handler = XformsAddRules(rulePath, bindPath, xmlWriter)
    parser.setContentHandler(handler)
    parser.setErrorHandler(handler)
    parser.setFeature("http://xml.org/sax/features/namespace-prefixes", True)
    parser.setProperty("http://xml.org/sax/properties/lexical-handler",
                       handler)

    stream = FileInputStream(templatePath)
    parser.parse(InputSource(stream))
    xmlWriter.close()
    stringWriter.close()
    return unicode(stringWriter)
コード例 #4
0
def deleteGenes(fileName, geneStarts):
    reader = XMLReaderFactory.createXMLReader()
    reader.entityResolver = reader.contentHandler = GeneDeleter(
        geneStarts, "profelis.temp.blastp.xml")
    reader.parse(fileName)
    os.remove(fileName)
    os.rename("profelis.temp.blastp.xml", fileName)
コード例 #5
0
    def _createReader(self, path, value, xmlWriter):
        u'''функция создания ридера для чтения файла настроек, с учетом указанного пути'''
        pathList = list()
        name = r"[a-zA-Z_][a-zA-Z_0-9]+"
        elementPatern = regexp.compile(r"""(%s)(?:\[(?:@(%s)=(?:'([^']+)'|\"([^\"]+)\")|([0-9]+))\])?(?:/@(%s))?""" % (name, name, name), regexp.UNICODE)
        lastEnd = -1
        for a in elementPatern.finditer(unicode(path)):
            if lastEnd + 1 != a.start(0) or (lastEnd > 0 and path[lastEnd]not in ('/', '\\')):
                raise CelestaException('Bad XPath expression')
            pathList.append(NodeProperties(a.groups()))
            lastEnd = a.end(0)

        parser = XMLReaderFactory.createXMLReader()
        handler = WriteSettings(pathList, xmlWriter, value)
        parser.setContentHandler(handler)
        parser.setErrorHandler(handler)
        parser.setFeature("http://xml.org/sax/features/namespace-prefixes", True)
        parser.setProperty("http://xml.org/sax/properties/lexical-handler", handler)

        stream = FileInputStream(self._getUserSettingsFilePath())
        parser.parse(InputSource(stream))
        stream.close()

        if not handler.result:
            stream = FileInputStream(self._getSettingsFilePath())
            parser.parse(InputSource(stream))
            stream.close()

        return handler.result
コード例 #6
0
def addGenes(fileName, source):
    reader = XMLReaderFactory.createXMLReader()
    reader.entityResolver = reader.contentHandler = GeneAdder(
        source, "profelis.temp.blastp.xml")
    reader.parse(fileName)
    os.remove(fileName)
    os.rename("profelis.temp.blastp.xml", fileName)
コード例 #7
0
ファイル: report.py プロジェクト: jarl-haggerty/neofelis
def report(name, genes, output):
  """
  name:   Name of the genome.
  genes:  A dictionary that maps query names to Iteration objects.
  output: Output file name without an extension.

  Writes a report of the contents of the blast searchs for the queries in
  genes into "name.html", "name.blastp.xml", and "name.xls".
  """
  reader = XMLReaderFactory.createXMLReader()
  reader.entityResolver = reader.contentHandler = BlastMerger(["extendedBlasts/" + name + ".blastp.xml", "intergenicBlasts/" + name + ".blastp.xml"], genes.keys(), output + ".blastp.xml", True)
  reader.parse("initialBlasts/" + name + ".blastp.xml")

  reader = XMLReaderFactory.createXMLReader()
  reader.entityResolver = reader.contentHandler = HTMLWriter(output + ".blastp.html")
  reader.parse(output + ".blastp.xml")

  writeSpreadsheet(genes.values(), output)
コード例 #8
0
ファイル: utils.py プロジェクト: pavithra03/neofelis
def parseBlast(fileName):
  """
  A function for parsing XML blast output.
  """
  reader = XMLReaderFactory.createXMLReader()
  reader.entityResolver = reader.contentHandler = BlastHandler()
  reader.parse(fileName)

  return dict(map(lambda iteration: (iteration.query, iteration), reader.getContentHandler().iterations))
コード例 #9
0
ファイル: xml.py プロジェクト: jarl-haggerty/profelis
 def startElement(self, uri, tag, name, attributes):
     if tag == "Iteration" and not self.added:
         self.added = True
         reader = XMLReaderFactory.createXMLReader()
         reader.entityResolver = reader.contentHandler = GeneWriter(self.output)
         try:
             reader.parse(self.source)
         except BreakParsingException:
             print "Hello"
     self.output.write("<" + tag + ">")
コード例 #10
0
 def startElement(self, uri, tag, name, attributes):
     if tag == "Iteration" and not self.added:
         self.added = True
         reader = XMLReaderFactory.createXMLReader()
         reader.entityResolver = reader.contentHandler = GeneWriter(
             self.output)
         try:
             reader.parse(self.source)
         except BreakParsingException:
             print "Hello"
     self.output.write("<" + tag + ">")
コード例 #11
0
ファイル: utils.py プロジェクト: jarl-haggerty/profelis
def parseBlast(fileName):
  """
  A function for parsing XML blast output.
  """
  reader = XMLReaderFactory.createXMLReader()
  reader.contentHandler = BlastHandler()
  reader.entityResolver = BlastHandler()
  reader.parse(fileName)

  for iteration in reader.contentHandler.iterations:
    iteration.xmlFile = fileName 
  return reader.contentHandler.database, reader.contentHandler.evalue, reader.contentHandler.iterations
コード例 #12
0
def parseBlast(fileName):
    """
  A function for parsing XML blast output.
  """
    reader = XMLReaderFactory.createXMLReader()
    reader.contentHandler = BlastHandler()
    reader.entityResolver = BlastHandler()
    reader.parse(fileName)

    for iteration in reader.contentHandler.iterations:
        iteration.xmlFile = fileName
    return reader.contentHandler.database, reader.contentHandler.evalue, reader.contentHandler.iterations
コード例 #13
0
ファイル: ParseLoader.py プロジェクト: pambule/hopper
    def load(self, filename, language):
    parser = XMLReaderFactory.createXMLReader()
    
    #if (filename.endsWith(".gz")):
        #input_src = InputSource(GZipInputStream(FileInputStream(filename)))
    #else:
    input_src = InputSource(filename)
    
    parser.contentHandler = ParseHandler(language)
    parser.parse(input_src)

    HibernateUtil.commitTransaction()
    HibernateUtil.closeSession()
コード例 #14
0
ファイル: dbutils.py プロジェクト: CourseOrchestra/syslib
    def uploadXML(self, action="ui"):
        '''
    функция реализует загрузку данных из xml в базу данных
'''
        parser = XMLReaderFactory.createXMLReader()
        handler = UploadXMLHandler(self.tableInstance, action)
        parser.setContentHandler(handler)
        parser.setErrorHandler(handler)
        parser.setFeature("http://xml.org/sax/features/namespace-prefixes",
                          True)
        parser.setProperty("http://xml.org/sax/properties/lexical-handler",
                           handler)
        parser.parse(InputSource(self.dataStream))
コード例 #15
0
 def __init__(self, rulePath, bindPath, xmlWriter):
     self.rulePath = rulePath
     self.bindPath = bindPath
     self.xmlWriter = xmlWriter
     self.parser = XMLReaderFactory.createXMLReader()
     handler = RulesWriter(self.xmlWriter)
     self.parser.setContentHandler(handler)
     self.parser.setErrorHandler(handler)
     self.parser.setFeature(
         "http://xml.org/sax/features/namespace-prefixes", True)
     self.parser.setProperty(
         "http://xml.org/sax/properties/lexical-handler", handler)
     self.state = 0
コード例 #16
0
ファイル: report.py プロジェクト: jarl-haggerty/neofelis
    def endElement(self, uri, tag, name):
        if tag == "BlastOutput_iterations":
            if self.sources:
                self.output.write("  ")
                reader = XMLReaderFactory.createXMLReader()
                reader.entityResolver = reader.contentHandler = BlastMerger(self.sources[1:], self.genes, self.output, False, self, self.iteration)
                try:
                    reader.parse(self.sources[0])
                except BreakParsingException:
                    if self.parent:
                        raise BreakParsingException()
                    else:
                        pass
            else:
                raise BreakParsingException()

        if self.iterationQueryDef:
            self.iterationQueryDef = False
            if self.iterationQueryDefString[:self.iterationQueryDefString.rfind(":")] in self.genes:
                self.printing = True
                self.holding = False
                self.output.write("".join(self.text))
                self.text = []
            else:
                self.printing = False
                self.holding = False
                self.text = []

        if self.printing:
            if self.holding:
                self.text += re.sub("\n\s*\n", "\n", "".join(self.whitespace)) + "</" + tag + ">"
            else:
                self.output.write(re.sub("\n\s*\n", "\n", "".join(self.whitespace)) + "</" + tag + ">")
            self.whitespace = []

        if tag == "Iteration":
            self.holding = False
            self.printing = True
コード例 #17
0
ファイル: report.py プロジェクト: jarl-haggerty/profelis
def report(name, genes, output):
  """
  name:   Name of the genome.
  genes:  A dictionary that maps query names to Iteration objects.
  output: Output file name without an extension.

  Writes a report of the contents of the blast searchs for the queries in
  genes into "<name>.dat" and "<name>.xls".
  """
  dataOutput = open(output + ".dat", "w")
  spreadsheetOutput = open(output + ".xls", "w")
  
  reader = XMLReaderFactory.createXMLReader()
  reader.setContentHandler(Collector(genes.keys(), dataOutput))
  reader.setEntityResolver(reader.getContentHandler())

  reader.parse("initialBlasts/" + name + ".blastp.xml")
  reader.parse("extendedBlasts/" + name + ".blastp.xml")
  reader.parse("intergenicBlasts/" + name + ".blastp.xml")

  writeSpreadsheet(genes.values(), spreadsheetOutput)
  
  dataOutput.close()
  spreadsheetOutput.close()
コード例 #18
0
ファイル: xml.py プロジェクト: jarl-haggerty/profelis
def writeHTML(fileName):
    reader = XMLReaderFactory.createXMLReader()
    reader.entityResolver = reader.contentHandler = HTMLWriter(fileName[:-4] + ".html" if fileName[-4:] == ".xml" else fileName + ".html")
    reader.parse(fileName)
コード例 #19
0
ファイル: xml.py プロジェクト: jarl-haggerty/profelis
def addGenes(fileName, source):
    reader = XMLReaderFactory.createXMLReader()
    reader.entityResolver = reader.contentHandler = GeneAdder(source, "profelis.temp.blastp.xml")
    reader.parse(fileName)
    os.remove(fileName)
    os.rename("profelis.temp.blastp.xml", fileName)
コード例 #20
0
ファイル: xml.py プロジェクト: jarl-haggerty/profelis
def deleteGenes(fileName, geneStarts):
    reader = XMLReaderFactory.createXMLReader()
    reader.entityResolver = reader.contentHandler = GeneDeleter(geneStarts, "profelis.temp.blastp.xml")
    reader.parse(fileName)
    os.remove(fileName)
    os.rename("profelis.temp.blastp.xml", fileName)
コード例 #21
0
    def __init__(self, encoding, namespace_separator):
        self.encoding = encoding
        self.CurrentLineNumber = 1
        self.CurrentColumnNumber = 0
        self._NextLineNumber = 1
        self._NextColumnNumber = 0
        self.ErrorLineNumber = -1
        self.ErrorColumnNumber = -1
        self.ErrorCode = None

        if namespace_separator is None:
            self.namespace_separator = namespace_separator
        elif isinstance(namespace_separator, basestring):
            self.namespace_separator = str(namespace_separator)
            if len(self.namespace_separator) > 1:
                error = ("namespace_separator must be at most one character, "
                         "omitted, or None")
                raise ValueError(error)
        else:
            error = ("ParserCreate() argument 2 must be string or None, "
                     "not %s" % type(namespace_separator).__name__)
            raise TypeError(error)

        # See http://bugs.jython.org/issue1537
        try:
            self._reader = XMLReaderFactory.createXMLReader(
                _mangled_xerces_parser_name)
        except:
            self._reader = XMLReaderFactory.createXMLReader(
                _xerces_parser_name)

        if self.namespace_separator is None:
            try:
                feature = "http://xml.org/sax/features/namespaces"
                self._reader.setFeature(feature, False)
            except SAXNotRecognizedException:
                error = ("namespace support cannot be disabled; "
                         "set namespace_separator to a string of length 1.")
                raise ValueError(error)

        self._base = None
        self._buffer_text = True
        self._returns_unicode = True

        self._data = StringBuilder()

        self._handler = XMLEventHandler(self)
        self._reader.setContentHandler(self._handler)
        self._reader.setErrorHandler(self._handler)
        self._reader.setDTDHandler(self._handler)
        self._reader.setEntityResolver(self._handler)

        sax_properties = ("lexical-handler", "declaration-handler")
        for name in sax_properties:
            try:
                name = "http://xml.org/sax/properties/" + name
                self._reader.setProperty(name, self._handler)
            except SAXNotRecognizedException:
                error = "can't set property %r" % name
                raise NotImplementedError(error)

        apache_features = (("nonvalidating/load-external-dtd", False), )
        for name, value in apache_features:
            try:
                name = "http://apache.org/xml/features/" + name
                self._reader.setFeature(name, value)
            except SAXNotRecognizedException:
                error = "can't set feature %r" % name
                raise NotImplementedError(error)

        # experimental
        #f = "http://xml.org/sax/features/external-general-entities"
        f = "http://xml.org/sax/features/external-parameter-entities"
        #self._reader.setFeature(f, False)

        # check
        f = "http://xml.org/sax/features/use-entity-resolver2"
        assert self._reader.getFeature(f)
コード例 #22
0
ファイル: xmltotext.py プロジェクト: jarl-haggerty/profelis
def xmlToText(input, output):
  reader = XMLReaderFactory.createXMLReader()
  translater = BlastTranslater(output)
  reader.setContentHandler(translater)
  reader.setEntityResolver(translater)
  reader.parse(input)
コード例 #23
0
ファイル: expat.py プロジェクト: abhijangda/DacapoInputSets
    def __init__(self, encoding, namespace_separator):
        self.encoding = encoding
        self.CurrentLineNumber = 1
        self.CurrentColumnNumber = 0
        self._NextLineNumber = 1
        self._NextColumnNumber = 0
        self.ErrorLineNumber = -1
        self.ErrorColumnNumber = -1
        self.ErrorCode = None

        if namespace_separator is None:
            self.namespace_separator = namespace_separator
        elif isinstance(namespace_separator, basestring):
            self.namespace_separator = str(namespace_separator)
            if len(self.namespace_separator) > 1:
                error = ("namespace_separator must be at most one character, "
                         "omitted, or None")
                raise ValueError(error)
        else:
            error = ("ParserCreate() argument 2 must be string or None, "
                     "not %s" % type(namespace_separator).__name__)
            raise TypeError(error)

        self._reader = XMLReaderFactory.createXMLReader(_xerces_parser)

        if self.namespace_separator is None:
            try:
                feature = "http://xml.org/sax/features/namespaces"
                self._reader.setFeature(feature, False)
            except SAXNotRecognizedException:
                error = ("namespace support cannot be disabled; "
                         "set namespace_separator to a string of length 1.")
                raise ValueError(error)

        self._base = None
        self._buffer_text = True
        self._returns_unicode = True

        self._data = StringBuilder()

        self._handler = XMLEventHandler(self)
        self._reader.setContentHandler(self._handler)
        self._reader.setErrorHandler(self._handler)
        self._reader.setDTDHandler(self._handler)
        self._reader.setEntityResolver(self._handler)

        sax_properties = ("lexical-handler", "declaration-handler")
        for name in sax_properties:
            try:
                name = "http://xml.org/sax/properties/" + name
                self._reader.setProperty(name, self._handler)
            except SAXNotRecognizedException:
                error = "can't set property %r" % name
                raise NotImplementedError(error)

        apache_features = (("nonvalidating/load-external-dtd", False),)
        for name, value in apache_features:
            try:
                name = "http://apache.org/xml/features/" + name
                self._reader.setFeature(name, value)
            except SAXNotRecognizedException:
                error = "can't set feature %r" % name
                raise NotImplementedError(error)

        # experimental
        #f = "http://xml.org/sax/features/external-general-entities"
        f = "http://xml.org/sax/features/external-parameter-entities"
        #self._reader.setFeature(f, False)

        # check
        f = "http://xml.org/sax/features/use-entity-resolver2"
        assert self._reader.getFeature(f)
コード例 #24
0
ファイル: xmltotext.py プロジェクト: jarl-haggerty/profelis
def xmlToText(input, output):
    reader = XMLReaderFactory.createXMLReader()
    translater = BlastTranslater(output)
    reader.setContentHandler(translater)
    reader.setEntityResolver(translater)
    reader.parse(input)
コード例 #25
0
def writeHTML(fileName):
    reader = XMLReaderFactory.createXMLReader()
    reader.entityResolver = reader.contentHandler = HTMLWriter(
        fileName[:-4] + ".html" if fileName[-4:] == ".xml" else fileName +
        ".html")
    reader.parse(fileName)