Exemplo n.º 1
0
def _compile_xsl(XSLT_FILE, XSLT_COMPILED_FILE):
    """
        compiling docbook stylesheet

        reference: http://155.210.85.193:8010/ccia/nodes/2005-03-18/compileXslt?xslt=/akara/akara.xslt
    """
    from Ft.Xml.Xslt.Processor import Processor
    from Ft.Xml.Xslt import Stylesheet
    from Ft.Xml import InputSource
    from Ft.Lib import Uri

    # New docbook processor
    db_processor = Processor()

    # Docbook Stylesheet
    my_sheet_uri = Uri.OsPathToUri(XSLT_FILE, 1)
    sty_isrc = InputSource.DefaultFactory.fromUri(my_sheet_uri)

    # Append Stylesheet
    db_processor.appendStylesheet(sty_isrc)

    # Pickled stylesheet will be self.abs_db_compiled_xsl file
    db_root = db_processor.stylesheet.root
    fw = file(XSLT_COMPILED_FILE, 'wb')
    cPickle.dump(db_root, fw)  # , protocol=2)
    fw.close()
Exemplo n.º 2
0
def processDocumentNode( c ):
    '''this executes the stylesheet node against the current node'''
    try:
        if not styleNodeSelected( c ): return
        proc = Processor()
        stylenode = stylenodes[ c ]
        pos = c.p
        c.selectPosition( stylenode )
        sIO = getString( c )
        mdom1 = minidom.parseString( sIO )
        sIO = str( mdom1.toxml() )
        hstring = str( stylenode.h )
        if hstring == "": hstring = "no headline"
        stylesource = InputSource.DefaultFactory.fromString( sIO, uri = hstring)
        proc.appendStylesheet( stylesource )
        c.selectPosition( pos )
        xmlnode = pos.v
        xIO = getString( c )
        mdom2 = minidom.parseString( xIO )
        xIO = str( mdom2.toxml())
        xhead = str( xmlnode.headString )
        if xhead == "": xhead = "no headline"
        xmlsource = InputSource.DefaultFactory.fromString( xIO, uri = xhead )
        result = proc.run( xmlsource )
        nhline = "xsl:transform of " + str( xmlnode.headString )
        p2 = pos.insertAfter() # tnode )
        p2.setBodyString(result)
        p2.setHeadString(nhline)
        c.redraw()

    except Exception as x:
        g.es( 'exception ' + str( x ))
    c.redraw()
Exemplo n.º 3
0
        def applyXslt(self,
                      xslStylesheet,
                      topLevelParams=None,
                      extFunctionMap=None,
                      baseUri='file:',
                      styleSheetCache=None):
            extFunctionMap = extFunctionMap or {}

            from Ft.Xml.Xslt.Processor import Processor
            processor = Processor()

            if styleSheetCache:
                styleSheet = styleSheetCache.getValue(xslStylesheet, baseUri)
                processor.appendStylesheetInstance(styleSheet, baseUri)
            else:
                processor.appendStylesheet(
                    InputSource.DefaultFactory.fromString(
                        xslStylesheet, baseUri))  #todo: fix baseUri

            for (k, v) in extFunctionMap.items():
                namespace, localName = k
                processor.registerExtensionFunction(namespace, localName, v)

            return processor.runNode(self.dom, None, 0,
                                     topLevelParams), processor.stylesheet
Exemplo n.º 4
0
def transform(xml, xsl):
    """
    A simple wrapper for 4XSLT.
    """
    from Ft.Xml.Xslt.Processor import Processor
    from Ft.Xml.InputSource import DefaultFactory
    proc = Processor()
    xslObj = DefaultFactory.fromString(xsl, "http://rantelope.com/")
    proc.appendStylesheet(xslObj)
    xmlObj = DefaultFactory.fromString(xml)
    return proc.run(xmlObj)
Exemplo n.º 5
0
    def build_dom_and_apply_style_sheet(self, xsl, file):
        #doc = xml.dom.minidom.Document()
        doc = implementation.createRootNode('file:///article.xml')

        self.app.ann_frame.build_xml(doc)

        xsltproc = Processor()
        xsltproc.appendStylesheet(DefaultFactory.fromUri(Uri.OsPathToUri(xsl)))
        output = xsltproc.runNode(doc, 'file:///article.xml')

        outFile = open(file, 'w')
        outFile.write(output)
        outFile.close()
Exemplo n.º 6
0
def Test(tester):
    # We don't use test_harness.XsltTest and friends because they hide away
    # the API details we're testing in this module.
    # See http://bugs.4suite.org/641693

    tester.startGroup("Test multiple stylesheet invokation")
    xp = Processor()
    xp.appendStylesheet(
        DefaultFactory.fromString(stylesheet_string, uri="data:ss"))
    result1 = xp.run(DefaultFactory.fromString(source_string, uri="data:src1"))
    result2 = xp.run(DefaultFactory.fromString(source_string, uri="data:src2"))
    tester.compare(result1, EXPECTED_1)
    tester.compare(result2, EXPECTED_1)
    tester.groupDone()
    return
Exemplo n.º 7
0
    def __transform_4suite(self, file, xsl_file, output, params):

        import codecs
        from Ft.Xml import InputSource
        from Ft.Xml.Xslt.Processor import Processor

        document = InputSource.DefaultFactory.fromUri(file)
        stylesheet = InputSource.DefaultFactory.fromUri(xsl_file)
            # there's also a fromString() method

        processor = Processor()
        processor.appendStylesheet(stylesheet)  
        result = processor.run(document, topLevelParams=params)
        (utf8_encode, utf8_decode, utf8_reader, utf8_writer) = codecs.lookup("utf-8")
        write_obj = utf8_writer(open(output, 'w'))
        write_obj.write(result)
        write_obj.close()
Exemplo n.º 8
0
    def get_processor(self, transform_hash, ext_functions=None, ext_elements=None):
        try:
            # First make sure we avoid race conditions...
            self._main_lock.acquire()
            if transform_hash not in self._granular_locks:
                self._granular_locks[transform_hash] = thread.allocate_lock()
        finally:
            self._main_lock.release()

        proc = None
        try:
            self._granular_locks[transform_hash].acquire()
            # If we do not have that stylesheet yet in the pool, let's add it
            if not self._processors.has_key(transform_hash):
                processor = Processor()
                self._processors[transform_hash] = processor_info(
                    thread.allocate_lock(), stat(transform_hash)[ST_MTIME], processor
                )
                for (ns, local), func in ext_functions.items():
                    processor.registerExtensionFunction(ns, local, func)
                for (ns, local), elem in ext_elements.items():
                    processor.registerExtensionElement(ns, local, elem)

                self._processors[transform_hash].instance.append_transform(iri.os_path_to_uri(transform_hash))
            # If the stylesheet has been modified, reload it
            elif stat(transform_hash)[ST_MTIME] != self._processors[transform_hash].last_modified:
                self._processors[transform_hash].instance.reset()
                self._processors[transform_hash].last_modified = stat(transform_hash)[ST_MTIME]
                self._processors[transform_hash].instance.append_transform(iri.os_path_to_uri(transform_hash))

            # now we can lock the processor...
            self._processors[transform_hash]['lock'].acquire()
            proc = self._processors[transform_hash].instance
        finally:
            self._granular_locks[transform_hash].release()
        # ... and return it
        return proc
Exemplo n.º 9
0
    def error(self, message):
        print "B³±d: " + message

    def fatal(self, message):
        print "B³±d krytyczny: " + message


# Otwórz pliki HTML i XSTL jako strumienie.
html = open('mojblog.html')
xsl = open('HTMLnaRSS.xsl')

# Przetwórz strumienie i utwórz z nich Ÿród³a wejœciowe.
parsedxml = InputSource.DefaultFactory.fromStream(html, "mojblog.html")
parsedxsl = InputSource.DefaultFactory.fromStream(xsl, "HTMLnaRSS.xsl")

# Utwórz nowy procesor, do³¹cz do niego arkusz stylu a nastêpnie przekszta³æ XML.
processor = Processor()
processor.appendStylesheet(parsedxsl)
HTML = processor.run(parsedxml)

# Zapisz wyjœciowy dokument RSS w pliku.
output = open("kanalRSS.xml", 'w')
output.write(HTML)
output.close

# Dokonaj walidacji kana³u RSS.
parser = xmlval.XMLValidator()
parser.set_error_handler(docErrorHandler(parser))
parser.parse_resource("kanalRSS.xml")
Exemplo n.º 10
0
    def format(self, formatter):
        """ Send the text. """
        _ = self._

        if not self.request.cfg.allow_xslt:
            # use plain text parser if XSLT is not allowed
            # can be activated in wikiconfig.py
            from MoinMoin.parser.text import Parser as TextParser
            self.request.write(
                formatter.sysmsg(1) + formatter.rawHTML(
                    _('XSLT option disabled, please look at HelpOnConfiguration.',
                      wiki=True)) + formatter.sysmsg(0))
            TextParser(self.raw, self.request).format(formatter)
            return

        try:
            # try importing Ft from 4suite
            # if import fails or its version is not 1.x, error msg
            from Ft.Xml import __version__ as ft_version
            assert ft_version.startswith('1.')
        except (ImportError, AssertionError):
            self.request.write(
                self.request.formatter.sysmsg(1) + self.request.formatter.text(
                    _('XSLT processing is not available, please install 4suite 1.x.'
                      )) + self.request.formatter.sysmsg(0))
        else:
            from Ft.Lib import Uri
            from Ft.Xml import InputSource
            from Ft.Xml.Xslt.Processor import Processor
            from Ft import FtException

            msg = None

            try:
                # location of SchemeRegisteryResolver has changed since 1.0a4
                if ft_version >= "1.0a4" or ft_version == "1.0" or (
                        "1.0.1" <= ft_version <= "1.0.9"):
                    # such version numbers suck!
                    import Ft.Lib.Resolvers  # Do not remove! it looks unused, but breaks when removed!!!

                class MoinResolver(Uri.SchemeRegistryResolver):
                    """ supports resolving self.base_uri for actual pages in MoinMoin """
                    def __init__(self, handlers, base_scheme):
                        Uri.SchemeRegistryResolver.__init__(self, handlers)
                        self.supportedSchemes.append(base_scheme)

                # setting up vars for xslt Processor
                out_file = StringIO.StringIO()
                wiki_resolver = MoinResolver(handlers={
                    self.base_scheme:
                    self._resolve_page,
                },
                                             base_scheme=self.base_scheme)
                input_factory = InputSource.InputSourceFactory(
                    resolver=wiki_resolver)

                page_uri = self.base_uri + wikiutil.url_quote(
                    formatter.page.page_name)
                # 4Suite needs an utf-8 encoded byte string instead of an unicode object
                raw = self.raw.strip().encode('utf-8')
                self.processor = Processor()
                self.append_stylesheet()  # hook, for extending this parser
                self.processor.run(input_factory.fromString(raw, uri=page_uri),
                                   outputStream=out_file)
                # Convert utf-8 encoded byte string into unicode
                result = out_file.getvalue().decode('utf-8')
                result = self.parse_result(
                    result)  # hook, for extending this parser

            except FtException, msg:
                etype = "XSLT"
            except Uri.UriException, msg:
                etype = "XSLT"
Exemplo n.º 11
0
 def get_processor(self):
     proc = Processor()
     if self.extensions:
         for ext in self.extensions:
             proc.registerExtensionFunction(*(ext))
     return proc
Exemplo n.º 12
0
def mongetattr(ins, attname):
    print "Aie!"
    return None


def monset(ins, d):
    print "On défini un truc sur le contexte"
    ancienset(ins, d)


def monsetattr(ins, attname, val):
    print "HeHo !"


print Ft.Xml.Xslt.XsltContext.XsltContext.__dict__.keys()
Ft.Xml.Xslt.XsltContext.XsltContext.__dict__['set'] = monset
Ft.Xml.Xslt.XsltContext.XsltContext.__dict__['addDocument'] = monsetattr
Ft.Xml.Xslt.XsltContext.XsltContext.__dict__['__setattr__'] = monsetattr
print Ft.Xml.Xslt.XsltContext.XsltContext.__dict__.keys()
xsltproc = Processor()

xsltproc.appendStylesheet(
    DefaultFactory.fromUri(
        "file:///home/t0rt00se/Travail/SILR3/pTrans/testset/persons_to_xhtml_list.xsl"
    ))
html = xsltproc.run(
    DefaultFactory.fromUri(
        "file:///home/t0rt00se/Travail/SILR3/pTrans/testset/persons.xml"))
print html