Ejemplo n.º 1
0
def Test(tester):
    tester.startGroup("instantiation of runNode")

    base = Uri.OsPathToUri(__file__, attemptAbsolute=True)
    src_uri = Uri.Absolutize('addr_book1.xml', base)
    sty_uri = Uri.Absolutize('addr_book1.xsl', base)

    tester.startTest("without whitespace preservation")
    p = Processor.Processor()
    node = Domlette.NonvalidatingReader.parseUri(src_uri)
    isrc = InputSource.DefaultFactory.fromUri(sty_uri)
    p.appendStylesheet(isrc)
    res = p.runNode(node, src_uri, ignorePis=True, preserveSrc=False)
    tester.compare(expected, res, func=TreeCompare.TreeCompare)
    tester.testDone()

    tester.startTest("with whitespace preservation")
    p = Processor.Processor()
    node = Domlette.NonvalidatingReader.parseUri(src_uri)
    isrc = InputSource.DefaultFactory.fromUri(sty_uri)
    p.appendStylesheet(isrc)
    res = p.runNode(node, src_uri, ignorePis=True, preserveSrc=True)
    tester.compare(expected, res, func=TreeCompare.TreeCompare)
    tester.testDone()

    tester.groupDone()
    return
Ejemplo n.º 2
0
def uixml(scwin, uixslt):
    extidx = uixslt.rindex('.')
    xslt2 = uixslt[:extidx] + "Post" + uixslt[extidx:]
    sctemplate = XMLHelper.writexml(scwin.asXML(True), UnicodeStringIO(), '',
                                    '\t', '\n')

    try:
        source = DefaultFactory.fromString(sctemplate, "urn:pass1")
        xsltUri = OsPathToUri(uixslt)
        transform = DefaultFactory.fromUri(xsltUri)

        processor = Processor.Processor()
        processor.appendStylesheet(transform)
        uixmlstr = processor.run(source)

        if os.path.exists(xslt2):
            source = DefaultFactory.fromString(uixmlstr, "urn:pass2")
            xsltUri = OsPathToUri(xslt2)
            transform = DefaultFactory.fromUri(xsltUri)

            processor = Processor.Processor()
            processor.appendStylesheet(transform)
            uixmlstr = processor.run(source)
    except Exception, e:
        QMessageBox.critical(None, 'Error!',
                             'Error with XSLT transform!\n\n' + str(e), 'OK')
        return
Ejemplo n.º 3
0
    def editConfig(self,
                   defaultoperation,
                   testoption,
                   erroroption,
                   target,
                   confignode,
                   targetnode=None):
        """
		Apply a edit-config request from the confignode to the targetnode.
		@type defaultoperation: MERGE_OPERATION | REPLACE_OPERATION | NONE_OPERATION 
		@param defaultoperation : as specified in NETCONF protocol
		@type testoption : SET | TEST_AND_SET 
		@param testoption : as specified in NETCONF protocol
		@type erroroption : STOP_ON_ERROR | IGNORE_ERROR | ROLL_BACK_ON_ERROR 
		@param erroroption : as specified in NETCONF protocol
		@type target : RUNNING_TARGET | CANDIDATE_TARGET | STARTUP_TARGET
		@param target : as specified in NETCONF protocol
		@type targetnode : string
		@param targetnode : if the target is RUNNING_TARGET or STARTUP_TARGET it will be ignored otherwise should be the node of the CANDIDATE_TARGET that this module should procees
		@rtype: ModuleReply
		@return: It returns a success or error message.
		** Relates to the netconf edit-config operation
		"""

        try:
            # Generate a stylesheet equivalent to the edit-config
            df = InputSource.DefaultFactory
            editXMLRequest = df.fromString(
                util.convertNodeToString(confignode), 'urn:dummy')
            stylesheet = df.fromUri("file:" + metaFile, 'urn:sty')
            p = Processor.Processor()
            p.appendStylesheet(stylesheet)
            wr = DomWriter.DomWriter()
            p.run(editXMLRequest, writer=wr)
            generatedStyleSheet = wr.getResult()

            # Apply the generated stylesheet to the source document
            inputStyleSheet = df.fromString(
                util.convertNodeToString(generatedStyleSheet), 'urn:sty')
            oldXMLDocument = self.getConfig(target).getXMLNodeReply()
            inputDocument = df.fromString(
                util.convertNodeToString(oldXMLDocument), 'urn:dummy')
            p = Processor.Processor()
            p.appendStylesheet(inputStyleSheet)
            wr = DomWriter.DomWriter()
            p.run(inputDocument, writer=wr)
            newXMLDoc = wr.getResult()

            # Copy the new document over the old one
            xmlReply = self.copyConfig("config", target, sourceNode=newXMLDoc)
            return xmlReply

        except Exception, exp:
            print str(exp)
            moduleReply = ModuleReply(error_type=ModuleReply.APPLICATION,
                                      error_tag=ModuleReply.OPERATION_FAILED,
                                      error_severity=ModuleReply.ERROR,
                                      error_message=str(exp))
            return moduleReply
Ejemplo n.º 4
0
 def __init__(self, transform):
     from Ft.Xml.Xslt import Processor
     from Ft.Xml import InputSource
     self.processor = Processor.Processor()
     trans_source = InputSource.DefaultFactory.fromString(
         transform, "CONVERTER")
     self.processor.appendStylesheet(trans_source)
def render(self, source_xml, content_type):
    """Render document using 4suite.

    """
    #pubUrl = self.REQUEST['PUBLISHED'].absolute_url()
    pubUrl = self.REQUEST['URL']
    proc = Processor.Processor()
    resolver = ZBaseUriResolver(self)

    factory = InputSource.InputSourceFactory(resolver=resolver)
    source = factory.fromString(self().encode(self.char_encoding), '/'.join(self.getPhysicalPath()))
    proc.appendStylesheet(source)


    if content_type in ['text/xml','text/html']:
        writer = XmlWriter.XmlWriter(proc.outputParams,StringIO.StringIO())
    else:
        writer = StringWriter.StringWriter(proc.outputParams,
                                           StringIO.StringIO())

    # Apply the stylesheet to the XMLTemplate. The result is
    # written to the output stream attribute of the writer so
    # grab that and send it back to the caller.
    proc.run(factory.fromString(source_xml),pubUrl,writer=writer)

    return writer.getStream().getvalue()
Ejemplo n.º 6
0
def Test(tester):
    tester.startGroup('pick stylesheet from xml-stylesheet PIs')
    for tup in tests:
        (title_st, source_st, expected_st) = tup[:3]
        errcode = None
        media = None
        if len(tup) > 3:
            errcode = tup[3]
        if len(tup) > 4:
            media = tup[4]
        expected = expected_st or ''
        source = test_harness.FileInfo(string=source_st, baseUri=uri)
        if media:
            proc = Processor.Processor()
            proc.mediaPref = media
            tester.startTest(title_st)
            isrc = DefaultFactory.fromString(source_st, uri)
            result = proc.run(isrc, ignorePis=0)
            tester.compare(expected_st, result, func=TreeCompare.TreeCompare)
            tester.testDone()
            del proc, isrc, result
        else:
            test_harness.XsltTest(tester,
                                  source, [],
                                  expected,
                                  exceptionCode=errcode,
                                  title=title_st,
                                  ignorePis=0)
    tester.groupDone()
    return
Ejemplo n.º 7
0
    def xml_xslt(self, transform, params=None, output=None):
        """
        Apply an XSLT transform directly to the bindery object
        This function is quite limited, and will only handle the
        simplest transforms.  If you find your transform does not work with it,
        serialize using xml() then use Ft.Xml.Xslt.transform, which is fully
        XSLT compliant.

        output - optional file-like object to which output is written
            (incrementally, as processed)
        if stream is given, output to stream, and return value is None
        If stream is not given return value is the transform result
        as a Python string (not Unicode)
        params - optional dictionary of stylesheet parameters, the keys of
            which may be given as unicode objects if they have no namespace,
            or as (uri, localname) tuples if they do.
        """
        from Ft.Xml.Xslt import Processor, _AttachStylesheetToProcessor
        from Ft.Xml import InputSource
        from Ft.Lib import Uri, Uuid
        from Ft.Xml.Lib.XmlString import IsXml

        params = params or {}
        processor = Processor.Processor()
        _AttachStylesheetToProcessor(transform, processor)

        return processor.runNode(self,
                                 topLevelParams=params,
                                 outputStream=output)
Ejemplo n.º 8
0
def test():

    #Test generating a file and running it
    #Test a simple addrbook

    #Build a ADDRBOOK xml file
    print "Address Book"
    src = ADDRBOOK_XML_1 + (ADDRBOOK_XML_ENTRY*5000) + ADDRBOOK_XML_2
    s = time.time()
    StylesheetCompilier.CompileString(ADDRBOOK,outFileName='addrbook')
    e = time.time()
    t = e - s
    print "Compile Time: %f" % (t)

    import addrbook
    st = addrbook.Stylesheet()
    s = time.time()
    st.executeString(src)
    e = time.time()
    cTime = e - s
    print "Compile Time: %f" % (cTime)

    from Ft.Xml.Xslt import Processor
    p = Processor.Processor()
    p.appendStylesheetString(ADDRBOOK)
    s = time.time()
    p.runString(src)
    e = time.time()
    pTime = e - s
    print "Processor Time: %f" % (pTime)
    print "Difference %f" % (pTime - cTime)
    print "Increase %f" % (100.0*(pTime - cTime)/pTime)
Ejemplo n.º 9
0
def pipp_map_view(context, xslt_file):
    ctx = context.processor.extensionParams[(NAMESPACE, 'context')]

    #--
    # Create the XSLT processor object. For efficiency there is a cache of these.
    #--
    xslt_file = ctx.abs_in_path(Conversions.StringValue(xslt_file))
    ctx.add_depends(xslt_file[len(ctx.in_root):])
    processor = processors.get(xslt_file)
    if not processor:
        processor = Processor.Processor()
        processor.registerExtensionModules(['pipp_xslt'])
        processor.appendStylesheet(
            InputSource.DefaultFactory.fromString(
                open(xslt_file).read(), xslt_file))
    processor.extensionParams[(NAMESPACE, 'context')] = ctx

    #--
    # Run the processor against state.xml and return the output.
    # If successful, store the processor object in a cache
    #--
    input = InputSource.DefaultFactory.fromUri(OsPathToUri(ctx.state_xml))
    output = processor.run(input)
    processors[xslt_file] = processor
    return output
Ejemplo n.º 10
0
 def processor(self):
     if not self._processor:
         _processor = Processor.Processor(
             stylesheetAltUris=[OsPathToUri(pipp_dir + os.path.sep)])
         _processor.registerExtensionModules(['pipp_xslt'])
         stylesheet = InputSource.DefaultFactory.fromUri(
             OsPathToUri(self.in_root + self.stylesheet_fname))
         _processor.appendStylesheet(stylesheet)
         self._processor = _processor
     return self._processor
Ejemplo n.º 11
0
def run_test(outFile, xmlFile, stylesheets):

    tempFileName = tempfile.mktemp()
    p = Processor.Processor()
    prof = profile.Profile()

    prof.runctx("profile_test(p,xmlFile,stylesheets)", globals(), locals())
    prof.dump_stats(tempFileName)

    return tempFileName
Ejemplo n.º 12
0
    def render_document(self, document, stylesheet, outfile):
        """
        This method is responsible for using 'stylesheet' to transform
        'document' to the file 'outfile'.

        Override this method to use a different XSLT rendering engine.
        """
        from Ft.Xml.InputSource import DefaultFactory
        from Ft.Xml.Xslt import Processor

        # Get a "clean" processor object
        if self._xslt_processor is None:
            self._xslt_processor = Processor.Processor()
        else:
            self._xslt_processor.reset()

        # Add the stylesheet to the processor object.
        isrc = DefaultFactory.fromUri(stylesheet.uri)
        try:
            self._xslt_processor.appendStylesheet(isrc)
        finally:
            isrc.close()

        params = {
            'name': self.distribution.get_name(),
            'version': self.distribution.version,
            'fullname': self.distribution.get_fullname(),
            'author': self.distribution.author,
            'author-email': self.distribution.author_email,
        }
        params.update(document.params)

        # Render the document
        isrc = DefaultFactory.fromUri(document.uri)
        try:
            if self.dry_run:
                stream = cStringIO.StringIO()
            else:
                self.mkpath(os.path.dirname(outfile))
                stream = open(outfile, 'w')
            try:
                try:
                    self._xslt_processor.run(isrc,
                                             topLevelParams=params,
                                             outputStream=stream)
                    stream.write('\n')
                finally:
                    stream.close()
            except:
                if not self.dry_run:
                    os.remove(outfile)
                raise
        finally:
            isrc.close()
        return
Ejemplo n.º 13
0
 def _transform_feed(self, feeduri, encoding):
     document = InputSource.DefaultFactory.fromUri(feeduri)  
     # Set encode to feedparser's guess to prevent unexpected
     # tokens for feeds with mismatching encoding declared.
     document.encoding = encoding
     stylesheet = InputSource.DefaultFactory.fromUri(RSS_2_RDF_XSL)
     processor = Processor.Processor()
     processor.appendStylesheet(stylesheet)
     logging.debug("Applying XSL transformation...")
     rdfstring = processor.run(document)
     return rdfstring
Ejemplo n.º 14
0
def transform(self, node):
    from Ft.Xml.Xslt import Processor, StylesheetReader, DomWriter
    from Ft.Xml import InputSource
    processor = Processor.Processor()
    xreader = StylesheetReader.StylesheetReader()
    style = xreader.fromDocument(self.applyElt.dom, baseUri="dummy")
    processor.appendStylesheetInstance(style)
    factory = InputSource.DefaultFactory
    isrc = factory.fromString("dummy", "dummy")
    resWriter = DomWriter.DomWriter()
    processor.execute(node, isrc, ignorePis=1, writer=resWriter)
    dom = resWriter.getResult()
    #print dom.firstChild.nodeValue
    return dom.firstChild
Ejemplo n.º 15
0
    def applyEditToXMLNode(self, confignode, target):

        metaFile = "Modules/meta.xsl"
        try:
            # Generate a stylesheet equivalent to the edit-config

            df = InputSource.DefaultFactory
            editXMLRequest = df.fromString(
                util.convertNodeToString(confignode), 'urn:dummy')
            stylesheet = df.fromUri("file:" + C.YENCAP_HOME + "/" + metaFile,
                                    'urn:sty')
            p = Processor.Processor()
            p.appendStylesheet(stylesheet)
            wr = DomWriter.DomWriter()
            p.run(editXMLRequest, writer=wr)
            generatedStyleSheet = wr.getResult()

            # Apply the generated stylesheet to the source document
            inputStyleSheet = df.fromString(
                util.convertNodeToString(generatedStyleSheet), 'urn:sty')
            inputDocument = df.fromString(util.convertNodeToString(target),
                                          'urn:dummy')
            p = Processor.Processor()
            p.appendStylesheet(inputStyleSheet)
            wr = DomWriter.DomWriter()
            p.run(inputDocument, writer=wr)
            newXMLDoc = wr.getResult()

            # Return the transformed document
            return newXMLDoc

        except Exception, exp:
            moduleReply = ModuleReply(error_type=ModuleReply.APPLICATION,
                                      error_tag=ModuleReply.OPERATION_FAILED,
                                      error_severity=ModuleReply.ERROR,
                                      error_message=str(exp))
            return moduleReply
Ejemplo n.º 16
0
    def parseConfigReport(self, filename, scxmldoc):
        processor = Processor.Processor()
        source = InputSource.DefaultFactory.fromString(
            XMLHelper.writexml(scxmldoc, UnicodeStringIO(), '', '\t', '\n'),
            "uri:sctemplate")

        try:
            xsltUri = OsPathToUri(filename)
            transform = InputSource.DefaultFactory.fromUri(xsltUri)

            processor.appendStylesheet(transform)
            self.reportHtml = processor.run(source)
        except Exception, e:
            QMessageBox.critical(
                None, 'Error!',
                'Error composing report ' + filename + "\n\n" + str(e), 'OK')
            return
Ejemplo n.º 17
0
 def transform(self, xmlData, xslData, base_url=""):
     """
     @param xmlData: the xml data to transform
     @param styleData: the xsl style sheet data to use in transform
     @return: a string version of the transformed document
     """
     try:
         processor = Processor.Processor()
         transform = InputSource.DefaultFactory.fromString(
             xslData, "http://spam.com/identity.xslt")
         source = InputSource.DefaultFactory.fromString(
             xmlData, "http://spam.com/doc.xml")
         processor.appendStylesheet(transform)
         result = processor.run(source)
         return result
     except:
         traceback.print_exc(file=sys.stdout)
         return ""
Ejemplo n.º 18
0
    def run(self, xslfile, xmlfile, outfile, opts=None, params=None):
        proc = Processor.Processor()
        proc.msgPrefix = ""
        proc.msgSuffix = "\n"
        factory = self.factory

        uri = OsPathToUri(xmlfile)
        xml = factory.fromUri(uri)

        uri = OsPathToUri(xslfile)
        xslt = factory.fromUri(uri, processIncludes=False)

        o = open(outfile, "w")
        proc.appendStylesheet(xslt)
        if params:
            rc = proc.run(xml, outputStream=o, topLevelParams=params)
        else:
            rc = proc.run(xml, outputStream=o)
        o.close()
Ejemplo n.º 19
0
    def parse_dom(self):
        super(XmlQuery, self).parse_dom()
        query_dom = self.dom
        name = query_dom.getAttribute('name')
        if name == '': return

        target = query_dom.getElementsByTagName('target')
        xsl = query_dom.getElementByTagName('xsl')
        if len(target) > 0 and len(xsl) > 0:
            target = target[0]
            xsl = xsl[0]
        else:
            raise Exception(
                "Either a URL or file for XML input must be specified")

        self.processor = Processor.Processor()
        if target.find('://') < 0:
            target = OsPathToUri(target)
        if xsl.find('://') < 0:
            xsl = OsPathToUri(xsl)

        self.target = target
        xsl_source = InputSource.DefaultFactory.fromUri(xsl)
        self.processor.appendStylesheet(transform)

        inputs_dom = query_dom.getElementsByTagName('inputs')
        inputs_dom = [i for i in inputs_dom if i in query_dom.childNodes]

        results_dom = query_dom.getElementsByTagName('results')[0]
        results_inputs_dom = results_dom.getElementsByTagName('inputs')

        self.function = self.find_function(results_dom)

        inputs = Inputs(inputs_dom)

        results_inputs = Inputs(results_inputs_dom)

        self.metadata['target_url'] = target
        self.metadata['xsl'] = xsl
        self.metadata['inputs'] = inputs
        self.metadata['results_inputs'] = results_inputs
        parse_attributes(self.metadata, query_dom)
Ejemplo n.º 20
0
    def applyXSLT(self, netconfReply):
        try:
            # Generate a stylesheet equivalent to the edit-config
            df = InputSource.DefaultFactory
            xmldoc = df.fromString(netconfReply, 'urn:dummy')
            xsldoc = df.fromUri("file:" + self.xsldocuri, 'urn:sty')
            p = Processor.Processor()
            p.appendStylesheet(xsldoc)
            wr = DomWriter.DomWriter()
            p.run(xmldoc, writer=wr)
            newHTMLDoc = wr.getResult()

            # Copy the new document over the old one
            return util.convertNodeToString(newHTMLDoc.documentElement)

        except Exception, exp:
            import traceback
            traceback.print_exc()
            return "Exception while applying XSLT of module %s: \n%s" % (
                self.name, str(exp))
Ejemplo n.º 21
0
def Transform(source, stylesheet, params=None, output=None):
    """
    Convenience function for applying an XSLT transform.  Returns
    a string.

    source - XML source document in the form of a a string (not Unicode
             object), file-like object (stream), file path, URI or
             Ft.Xml.InputSource.InputSource instance.  If string or stream
             it must be self-contained  XML (i.e. not requiring access to
             any other resource such as external entities or includes)
    stylesheet - XSLT document in the form of a string, stream, URL,
                 file path or Ft.Xml.InputSource.InputSource instance
    params - optional dictionary of stylesheet parameters, the keys of
             which may be given as unicode objects if they have no namespace,
             or as (uri, localname) tuples if they do.
    output - optional file-like object to which output is written (incrementally, as processed)
    """
    #do the imports within the function: a tad bit less efficient, but
    #avoid circular crap
    from Ft.Xml.Xslt import Processor
    from Ft.Xml import InputSource
    from Ft.Lib import Uri, Uuid
    from Ft.Xml.Lib.XmlString import IsXml

    params = params or {}
    processor = Processor.Processor()
    _AttachStylesheetToProcessor(stylesheet, processor)
    if isinstance(source, InputSource.InputSource):
        pass
    elif hasattr(source, 'read'):
        #Create dummy Uri to use as base
        dummy_uri = 'urn:uuid:' + Uuid.UuidAsString(Uuid.GenerateUuid())
        source = InputSource.DefaultFactory.fromStream(source, dummy_uri)
    elif IsXml(source):
        dummy_uri = 'urn:uuid:' + Uuid.UuidAsString(Uuid.GenerateUuid())
        source = InputSource.DefaultFactory.fromString(source, dummy_uri)
    elif Uri.IsAbsolute(source):  # or not os.path.isfile(source):
        source = InputSource.DefaultFactory.fromUri(source)
    else:
        source = InputSource.DefaultFactory.fromUri(Uri.OsPathToUri(source))
    return processor.run(source, topLevelParams=params, outputStream=output)
Ejemplo n.º 22
0
def format(xmltext, template_filename=None, template_source=None):
    """
    Processes an XML text according to a template, and returns the result.

    The template can be given either by name (or by path) or by source.
    If source is given, name is ignored.

    bibformat_xslt_engine will look for template_filename in standard directories
    for templates. If not found, template_filename will be assumed to be a path to
    a template. If none can be found, return None.

    @param xmltext: The string representation of the XML to process
    @param template_filename: The name of the template to use for the processing
    @param template_source: The configuration describing the processing.
    @return: the transformed XML text.
    """
    if processor_type == -1:
        # No XSLT processor found
        sys.stderr.write('No XSLT processor could be found.')
        #sys.exit(1)

    # Retrieve template and read it
    if template_source:
        template = template_source
    elif template_filename:
        try:
            path_to_templates = (CFG_BIBFORMAT_TEMPLATES_PATH + os.sep +
                                 template_filename)
            if os.path.exists(path_to_templates):
                template = file(path_to_templates).read()
            elif os.path.exists(template_filename):
                template = file(template_filename).read()
            else:
                sys.stderr.write(template_filename + ' does not exist.')
                return None
        except IOError:
            sys.stderr.write(template_filename + ' could not be read.')
            return None
    else:
        sys.stderr.write(template_filename + ' was not given.')
        return None

    # Some massaging of the input to avoid the default namespace issue
    # in XPath. More elegant solution might be found though.
    xmltext = xmltext.replace('xmlns="http://www.loc.gov/MARC21/slim"', '')

    # For older MARCXML records stored in bibfmt with empty indicators
    xmltext = xmltext.replace('ind1=""', 'ind1=" "')
    xmltext = xmltext.replace('ind2=""', 'ind2=" "')

    result = ""
    if processor_type == 0:
        # libxml2 & libxslt

        # Register BibFormat functions for use in XSL
        libxslt.registerExtModuleFunction("creation_date",
                                          CFG_BIBFORMAT_FUNCTION_NS,
                                          get_creation_date_libxslt)
        libxslt.registerExtModuleFunction("modification_date",
                                          CFG_BIBFORMAT_FUNCTION_NS,
                                          get_modification_date_libxslt)
        libxslt.registerExtModuleFunction("eval_bibformat",
                                          CFG_BIBFORMAT_FUNCTION_NS,
                                          eval_bibformat_libxslt)
        # Load template and source
        template_xml = libxml2.parseDoc(template)
        processor = libxslt.parseStylesheetDoc(template_xml)
        source = libxml2.parseDoc(xmltext)

        # Transform
        result_object = processor.applyStylesheet(source, None)
        try:
            result = processor.saveResultToString(result_object)
        except SystemError:
            # Catch an exception thrown when result is empty,
            # due to a bug in libxslt
            result = ''

        # Deallocate
        processor.freeStylesheet()
        source.freeDoc()
        result_object.freeDoc()

    elif processor_type == 1:
        # 4suite

        # Init
        processor = Processor.Processor()

        # Register BibFormat functions for use in XSL
        processor.registerExtensionFunction(CFG_BIBFORMAT_FUNCTION_NS,
                                            "creation_date",
                                            get_creation_date_4suite)
        processor.registerExtensionFunction(CFG_BIBFORMAT_FUNCTION_NS,
                                            "modification_date",
                                            get_modification_date_4suite)
        processor.registerExtensionFunction(CFG_BIBFORMAT_FUNCTION_NS,
                                            "eval_bibformat",
                                            eval_bibformat_4suite)
        # Load template and source
        transform = InputSource.DefaultFactory.fromString(template,
                                                          uri=CFG_SITE_URL)
        source = InputSource.DefaultFactory.fromString(xmltext,
                                                       uri=CFG_SITE_URL)
        processor.appendStylesheet(transform)

        # Transform
        result = processor.run(source)
    else:
        sys.stderr.write("No XSLT processor could be found")

    return result
Ejemplo n.º 23
0
def process(doc, out_enc):
    proc = Processor.Processor()
    stylesheet = xslt_identity % (out_enc, )
    proc.appendStylesheetString(stylesheet)
    return proc.runNode(doc)
Ejemplo n.º 24
0
            return None

        # Transform
        result_object = processor.applyStylesheet(source, None)
        result = processor.saveResultToString(result_object)

        # Deallocate
        processor.freeStylesheet()
        source.freeDoc()
        result_object.freeDoc()

    elif processor_type == 1:
        # 4suite

        # Init
        processor = Processor.Processor()

        # Register BibConvert functions for use in XSL
        processor.registerExtensionFunction(CFG_BIBCONVERT_FUNCTION_NS,
                                            "format",
                                            bibconvert_function_4suite)

        # Load template and source
        transform = InputSource.DefaultFactory.fromString(template,
                                                          uri=CFG_SITE_URL)
        source = InputSource.DefaultFactory.fromString(xmltext,
                                                       uri=CFG_SITE_URL)
        try:
            processor.appendStylesheet(transform)
        except XsltException, e:
            sys.stderr.write('Parsing XSL template failed:\n' + str(e))
Ejemplo n.º 25
0
 def __init__(self, quiet):
     self.xslt_processor = Processor.Processor()
     self.xslt_params = {}
     self.quiet = quiet
Ejemplo n.º 26
0
def XsltTest(tester,
             sourceXml,
             stylesheets,
             expected,
             compareFunc=None,
             ignorePis=1,
             topLevelParams=None,
             extensionModules=None,
             exceptionClass=XsltException,
             exceptionCode=None,
             stylesheetInputFactory=None,
             documentInputFactory=None,
             stylesheetAltUris=None,
             title='',
             funcArgs=None):
    """
    Common function to perform an XSLT transformation and compare the
    results through the tester.

    title is a short name that describes the test.

    tester is an Ft.Lib.TestSuite.Tester instance.

    sourceXml is a FileInfo instance for the source document.

    stylesheets is a list of FileInfo instances for the stylesheet(s).

    expected is a string to compare the actual transformation result to.

    compareFunc is a cmp()-like function to use to do the comparison.
    It defaults to whatever the tester's default is; usually cmp().
    funcArgs is a dictionary of keyword arguments to pass to the
    comparison function, if it accepts keyword arguments.

    ignorePis, topLevelParams, extensionModules, stylesheetAltUris are
    as documented in Ft.Xml.Xslt.Processor.Processor.

    exceptionCode is the expected exception code, if the test is
    intended to generate an exception.

    documentInputFactory, stylesheetInputFactory are InputSource
    factories to use when resolving references to external URIs from
    within the source document or stylesheet(s), respectively. Defaults
    for both are Ft.Xml.InputSource.DefaultFactory.
    """
    # reset the counter for generate-id
    g_idmap.clear()

    if not title:
        title = 'Source %(source)s' % (tester.test_data)
    tester.startTest(title)

    # Create the processor
    processor = Processor.Processor(stylesheetAltUris=stylesheetAltUris)
    processor.registerExtensionModules([__name__])
    if extensionModules:
        processor.registerExtensionModules(extensionModules)

    # Setup document input for the processor
    factory = documentInputFactory or InputSource.DefaultFactory
    reader = Domlette._Reader(tester.test_data['module'].NonvalParse,
                              kwargs={'readExtDtd': READ_EXTERNAL_DTD})
    reader.inputSourceFactory = factory
    processor.setDocumentReader(reader)

    # Do the transformation
    try:
        # Add the stylesheets to the processor
        factory = stylesheetInputFactory or InputSource.DefaultFactory
        for stylesheet in stylesheets:
            processor.appendStylesheet(stylesheet.toInputSource(factory))

        result = processor.run(sourceXml.toInputSource(factory),
                               ignorePis=ignorePis,
                               topLevelParams=topLevelParams)
    except exceptionClass, exception:
        if exceptionCode is None:
            # No exception was expected
            estr = _PrettifyException(exceptionClass, exception.errorCode)
            tester.exception('Unexpected exception ' + estr)
        else:
            # Compare the exception result
            expected = _PrettifyException(exceptionClass, exceptionCode)
            compared = _PrettifyException(exceptionClass, exception.errorCode)
            tester.compare(expected, compared, stackLevel=2)
Ejemplo n.º 27
0
    def editConfig(self,
                   defaultoperation,
                   testoption,
                   erroroption,
                   target,
                   confignode,
                   targetnode=None):
        """
        Apply a edit-config request from the confignode to the targetnode.
        @type defaultoperation: MERGE_OPERATION | REPLACE_OPERATION | NONE_OPERATION 
        @param defaultoperation : as specified in NETCONF protocol
        @type testoption : SET | TEST_AND_SET 
        @param testoption : as specified in NETCONF protocol
        @type erroroption : STOP_ON_ERROR | IGNORE_ERROR | ROLL_BACK_ON_ERROR 
        @param erroroption : as specified in NETCONF protocol
        @type target : RUNNING_TARGET | CANDIDATE_TARGET | STARTUP_TARGET
        @param target : as specified in NETCONF protocol
        @type targetnode : string
        @param targetnode : if the target is RUNNING_TARGET or STARTUP_TARGET it will be ignored otherwise should be the node of the CANDIDATE_TARGET that this module should procees
        @rtype: ModuleReply
        @return: It returns a success or error message.
        ** Relates to the netconf edit-config operation
        """

        try:
            # Generate a stylesheet equivalent to the edit-config
            df = InputSource.DefaultFactory
            editXMLRequest = df.fromString(
                util.convertNodeToString(confignode), 'urn:dummy')
            stylesheet = df.fromUri("file:" + metaFile, 'urn:sty')
            p = Processor.Processor()
            p.appendStylesheet(stylesheet)
            wr = DomWriter.DomWriter()
            p.run(editXMLRequest, writer=wr)
            generatedStyleSheet = wr.getResult()

            # Apply the generated stylesheet to the source document
            inputStyleSheet = df.fromString(
                util.convertNodeToString(generatedStyleSheet), 'urn:sty')
            oldXMLDocument = self.getConfig(target).getXMLNodeReply()
            inputDocument = df.fromString(
                util.convertNodeToString(oldXMLDocument), 'urn:dummy')
            p = Processor.Processor()
            p.appendStylesheet(inputStyleSheet)
            wr = DomWriter.DomWriter()
            p.run(inputDocument, writer=wr)
            newXMLDoc = wr.getResult()
            newOLSRRootNode = newXMLDoc.childNodes[0]

            # Copy the data to the olsr config file
            file_generator = Generator(self.namespace)
            file_generator.transform(newOLSRRootNode)

            print "new OLSR config is \n"
            PrettyPrint(newXMLDoc.childNodes[0])

            if (newOLSRRootNode != None):
                xmlreply = ModuleReply(replynode=newOLSRRootNode)

            else:
                xmlreply = ModuleReply(
                    error_type=ModuleReply.APPLICATION,
                    error_tag=ModuleReply.OPERATION_NOT_SUPPORTED,
                    error_severity=ModuleReply.ERROR,
                    error_message=
                    "Config generator from Module %s replied with None." %
                    self.name)

            return xmlreply

            # (Re)start the olsr process on the device, if it is running
#            p = OLSR_System()
#            p.start_new_olsr_instance()

#            xmlReply = self.copyConfig("config", target, sourceNode = newXMLDoc)
#            return xmlReply

        except Exception, exp:
            print str(exp)
            moduleReply = ModuleReply(error_type=ModuleReply.APPLICATION,
                                      error_tag=ModuleReply.OPERATION_FAILED,
                                      error_severity=ModuleReply.ERROR,
                                      error_message=str(exp))
            return moduleReply
Ejemplo n.º 28
0
def Run(options, args):

    stacktrace_on_error = options.has_key('stacktrace-on-error')

    # -- Set up output streams (will die if files unwritable) ----------
    # (assumes output destinations have been checked for uniqueness)

    if options.has_key('compile'):
        output_flags = "wb"
    else:
        output_flags = "w"

    out_file = options.has_key('outfile') \
               and open(options['outfile'], output_flags) or sys.stdout

    trace_file = None
    if options.has_key('trace'):
        trace_file_name = options.get('trace-file')
        if trace_file_name:
            trace_file_name = os.path.abspath(trace_file_name)

        out_file_name = options.get('outfile')
        if out_file_name:
            out_file_name = os.path.abspath(out_file_name)

        trace_file = options.has_key('trace-file') \
                     and open(options['trace-file'], 'w') or sys.stderr

    # -- Set up XSLT processor (without stylesheets) -------------------

    # gather alt base URIs for xsl:include/import resolution
    #
    # An ordered list of absolute URIs is derived from these sources:
    #  1. command-line option(s) alt-sty-uri=../../foo.xml
    #  2. command-line option(s) alt-sty-path=C:\foo.xml
    #  3. environment variable XSLTINCLUDE=\a\b\foo.xml
    alt_sty_uris = options.get('alt-sty-uri', [])
    if type(alt_sty_uris) != list:
        alt_sty_uris = [alt_sty_uris]

    alt_sty_paths = options.get('alt-sty-path', [])
    if type(alt_sty_paths) != list:
        alt_sty_paths = [alt_sty_paths]

    more_sty_uris = [
        OsPathToUri(path, attemptAbsolute=1) for path in alt_sty_paths
    ]
    alt_sty_uris.extend(more_sty_uris)

    if os.environ.has_key('XSLTINCLUDE'):
        more_sty_uris = [
            OsPathToUri(path, attemptAbsolute=1)
            for path in os.environ["XSLTINCLUDE"].split(os.pathsep)
        ]
        alt_sty_uris.extend(more_sty_uris)

    del more_sty_uris

    # tracing requires special setup.
    if options.has_key('trace'):
        from Ft.Xml.Xslt import ExtendedProcessingElements, StylesheetHandler
        processor = ExtendedProcessingElements.ExtendedProcessor(
            stylesheetAltUris=alt_sty_uris)
        processor._4xslt_trace = True
        processor._4xslt_traceStream = trace_file
        StylesheetHandler._ELEMENT_MAPPING = ExtendedProcessingElements.GetMappings(
        )
    else:
        processor = Processor.Processor(stylesheetAltUris=alt_sty_uris)

    # media prefs affect xsl:stylesheet PI selection
    processor.mediaPref = options.get('media', None)

    # register extension modules
    moduleList = os.environ.get("EXTMODULES")
    if moduleList:
        processor.registerExtensionModules(moduleList.split(":"))

    # set up the source document reader
    from Ft.Xml import Domlette
    validate_flag = options.has_key('validate')
    if validate_flag:
        reader = Domlette.ValidatingReader
    else:
        reader = Domlette.NonvalidatingReader
    processor.setDocumentReader(reader)

    #Customize message behavior
    if options.has_key('no-messages'):
        processor.messageControl(1)
    else:
        processor.messageControl(0)
        if options.has_key('msg-prefix'):
            prefix = options['msg-prefix']
            prefix = prefix.replace('\\n', '\n')
            prefix = prefix.replace('\\r', '\r')
            prefix = prefix.replace('\\t', '\t')
            processor.msgPrefix = prefix
        if options.has_key('msg-suffix'):
            suffix = options['msg-suffix']
            suffix = suffix.replace('\\n', '\n')
            suffix = suffix.replace('\\r', '\r')
            suffix = suffix.replace('\\t', '\t')
            processor.msgSuffix = suffix

    # -- Handle compile operation --------------------------------------

    if options.has_key('compile'):
        xinclude = not options.has_key('noxinclude')
        all_source_args = [args['source-uri']] + args['stylesheet-uri']
        try:
            sty_isrcs = map(
                lambda arg: StySourceArgToInputSource(
                    arg,
                    DefaultFactory,
                    processIncludes=xinclude,
                    stylesheetAltUris=alt_sty_uris), all_source_args)
            for isrc in sty_isrcs:
                processor.appendStylesheet(isrc)
                CloseStream(isrc, quiet=True)

            # use better pickle format in Python 2.3 and up
            if hasattr(cPickle, 'HIGHEST_PROTOCOL'):
                cPickle.dump(processor.stylesheet.root, out_file,
                             cPickle.HIGHEST_PROTOCOL)
            else:
                cPickle.dump(processor.stylesheet.root, out_file, 1)

        except Exception, e:
            ReportFatalException(e, stacktrace_on_error)

        CloseStream(out_file, quiet=True)

        if out_file is sys.stdout:
            dest = 'standard output'
        elif hasattr(out_file, 'name'):
            dest = out_file.name
        elif options.has_key('outfile'):
            dest = options['outfile']
        else:
            dest = 'unknown destination(!)'
        sys.stderr.write('Compiled stylesheet written to %s.\n' % dest)
        sys.stderr.flush()
        return