def transformReport(self, stylesheet, xml, output, params): from java.io import FileInputStream from java.io import FileOutputStream from java.io import ByteArrayOutputStream from javax.xml.transform import TransformerFactory from javax.xml.transform.stream import StreamSource from javax.xml.transform.stream import StreamResult self.xsl = FileInputStream("%s" % stylesheet) self.xml = FileInputStream("%s" % xml) self.html = FileOutputStream("%s" % output) try: self.xslSource = StreamSource(self.xsl) self.tfactory = TransformerFactory.newInstance() self.xslTemplate = self.tfactory.newTemplates(self.xslSource) self.transformer = self.xslTemplate.newTransformer() self.source = StreamSource(self.xml) self.result = StreamResult(self.html) for self.key, self.value in params.items(): self.transformer.setParameter(self.key, self.value) self.transformer.transform(self.source, self.result) finally: self.xsl.close() self.xml.close() self.html.close()
def __init__(self, xsl_path, **params): from javax.xml.transform import URIResolver from javax.xml.transform import TransformerFactory from javax.xml.transform.stream import StreamSource from java.io import FileInputStream xsl_path = os.path.abspath(xsl_path) xsl_base = os.path.dirname(xsl_path) xsl_fis = FileInputStream(xsl_path) xsl_source = StreamSource(xsl_fis) class BaseURIResolver(URIResolver): def __init__(self, base): self.base = base def resolve(self, href, base): path = os.path.join(self.base, href) path = os.path.abspath(path) fis = FileInputStream(path) return StreamSource(fis) uri_resolver = BaseURIResolver(xsl_base) xslt_factory = TransformerFactory.newInstance() xslt_factory.setURIResolver(uri_resolver) self.transformer = xslt_factory.newTransformer(xsl_source) for k, v in params.items(): self.transformer.setParameter(k, unicode(v))
def _transform(self, input, output): from javax.xml.transform.stream import StreamSource from javax.xml.transform.stream import StreamResult inp_source = StreamSource(input) out_result = StreamResult(output) self.transformer.transform(inp_source, out_result) return dict()
def transform(inp_path, out_path): inp_path = os.path.abspath(inp_path) out_path = os.path.abspath(out_path) inp_fis = FileInputStream(inp_path) out_fos = FileOutputStream(out_path) inp_source = StreamSource(inp_fis) out_result = StreamResult(out_fos) transformer.transform(inp_source, out_result) return dict()
def handler(environ, start_response): reload(sys) sys.setdefaultencoding('UTF8') welcomeString = "<html><head><title>atom2rss converter • Atom to RSS2 converter</title><style>body { padding: 20px 40px; font-family: Verdana, Helvetica, Sans-Serif; font-size: medium; }</style></head><body><form method=\"post\"><h1>atom2rss converter written with Jython</h1><p>This tool will let you convert your atom 1.0 feed into an RSS2 feed that can be imported into WordPress.</p><p>Please read the full instructions before starting.</p><p><input type=\"text\" name=\"atom\" style=\"width: 400px;\"><input type=\"submit\" value=\"Convert\"></p><h2>Instructions</h2><p><strong>Step 1</strong>: Enter the url of an atom feed urls, e.g. <i>http://yoursite.com/atom.xml</i><br /></p><p><strong>Step 2</strong>: After clicking the \"Convert\" button, head to File / Save As... and save the file as rss.xml to your desktop.</p><p><strong>Step 3</strong>: Use this rss.xml file to import your data into WordPress under Import / RSS.</p><h2>About</h2><p>This tool is online as a convenience designed by <a href=\"http://kevin.9511.net/\">Kevin Li</a>.</p><p>Your can use it to import GoogleReader or Blogger data into Wordpress.</p></form></body></html>" response_parts = [] header_str = '' if environ['REQUEST_METHOD'] == 'POST': post = environ['j2ee.request'] if post.getParameterValues('atom') is None: bs = welcomeString else: try: atom = post.getParameterValues('atom')[0] atomUrl = URL(str(atom)) atomSource = StreamSource( InputStreamReader(atomUrl.openStream(), "utf-8")) file = open(os.path.join(os.getcwd(), 'webapp/atom2rss.xsl')) xsltString = file.read() file.close() xsltSource = StreamSource(StringReader(xsltString)) outputBuffer = StringWriter() transFactory = javax.xml.transform.TransformerFactory.newInstance( "org.apache.xalan.processor.TransformerFactoryImpl", Thread.currentThread().getContextClassLoader()) transformer = transFactory.newTransformer(xsltSource) transformer.transform(atomSource, StreamResult(outputBuffer)) bs = outputBuffer.buffer.toString() header_str = 'text/xml;charset=utf-8' except MalformedURLException, mue: bs = "url format error" except TransformerException, te: bs = "transforme failed" except IOException, ie: bs = ie.getMessage()
def resolve(self, href, base): self.__logger.debug('default_base: %r', self.base) self.__logger.debug('href: %r', href) self.__logger.debug('base: %r', base) if base is None: base = self.base if base is not None: href = urljoin(base, href) else: href = href href = urlparse(href) # if href is not a URL if not href.scheme and not href.hostname: return StreamSource(File(href.path))
def xslt_compile(xsl_path): from javax.xml.transform import URIResolver from javax.xml.transform import TransformerFactory from javax.xml.transform.stream import StreamSource from javax.xml.transform.stream import StreamResult from java.io import FileInputStream from java.io import FileOutputStream import os.path xsl_path = os.path.abspath(xsl_path) xsl_base = os.path.dirname(xsl_path) xsl_fis = FileInputStream(xsl_path) xsl_source = StreamSource(xsl_fis) class BaseURIResolver(URIResolver): def __init__(self, base): self.base = base def resolve(self, href, base): path = os.path.join(self.base, href) path = os.path.abspath(path) fis = FileInputStream(path) return StreamSource(fis) uri_resolver = BaseURIResolver(xsl_base) xslt_factory = TransformerFactory.newInstance() xslt_factory.setURIResolver(uri_resolver) transformer = xslt_factory.newTransformer(xsl_source) def transform(inp_path, out_path): inp_path = os.path.abspath(inp_path) out_path = os.path.abspath(out_path) inp_fis = FileInputStream(inp_path) out_fos = FileOutputStream(out_path) inp_source = StreamSource(inp_fis) out_result = StreamResult(out_fos) transformer.transform(inp_source, out_result) return dict() return transform
def transform(xmldoc, xslt=config.defualt_xslt): ''' Runs the transform from the specified xslt against the provided document. The transformer is only loaded on the first run and then kept in memory for re-use. ''' global _transform if _transform is None: tFactory = TransformerFactory.newInstance() tFactory.setAttribute( 'http://saxon.sf.net/feature/licenseFileLocation', '/etc/saxon-license.lic') try: _transform = tFactory.newTransformer(StreamSource(JavaFile(xslt))) except TransformerConfigurationException, tce: print tce print '*' * 70 print 'This is likely that your license file for saxon is '\ 'missing or that there is a genuine error in the XSLT'
def transform(xlst, xmldoc, docuuid): ''' Runs the transform from the specified xslt against the provided document. The transformer is only loaded on the first run and then kept in memory for re-use. ''' global _transform global _errors global _count if _transform is None: tFactory = TransformerFactory.newInstance() try: _transform = tFactory.newTransformer(StreamSource(JavaFile(xslt))) except TransformerConfigurationException, tce: print tce print '*' * 70 print 'This is likely that your license file for saxon is '\ 'missing or that there is a genuine error in the XSLT' sys.exit(1)
def transform(xmldoc, xslt=config.defualt_xslt): ''' Runs the transform from the specified xslt against the provided document. The transformer is only loaded on the first run and then kept in memory for re-use. ''' global _transform if _transform is None: tFactory = TransformerFactory.newInstance() tFactory.setAttribute('http://saxon.sf.net/feature/licenseFileLocation', '/etc/saxon-license.lic') # JJ: not sure I have the right syntax here, but can Saxon be set to continue on error? #10/21. agreed to try and run a pass against a "minimal transform" in the event that an error is thrown here. Will work on XSLT tFactory.setAttribute(FeatureKeys.RECOVERY_POLICY, new Integer(Controller.RECOVER_SILENTLY)); # try: _transform = tFactory.newTransformer(StreamSource(JavaFile(xslt))) except TransformerConfigurationException, tce: print tce print '*' * 70 print 'This is likely that your license file for saxon is '\ 'missing or that there is a genuine error in the XSLT'
def test_xsl_stream(self): xsl_source = StreamSource(self.xsl_path) result = transform(xsl_source, src_source) #print result self.assertTrue('world' in result)
def resolve(self, href, base): path = os.path.join(self.base, href) path = os.path.abspath(path) fis = FileInputStream(path) return StreamSource(fis)
print tce print '*' * 70 print 'This is likely that your license file for saxon is '\ 'missing or that there is a genuine error in the XSLT' sys.exit(1) _count = _count + 1 if _count % 1000 == 0: System.gc() fid, path, = tempfile.mkstemp() os.close(fid) try: print '\r + Processing document %s' % (docuuid, ), _transform.transform(StreamSource(StringReader(xmldoc)), StreamResult(JavaFile(path))) f = open(path) store_document_result(f.read(), docuuid) f.close() os.remove(path) except TransformerException, e: _errors = _errors + 1 msg = "Error: %s\nDoc UUID: %s\n" % (e, docuuid) store_document_result("", docuuid, msg) logging.error(msg) def get_document_count(connection): '''
def xsltHtml(xslt,xmlcontent) : transformer = _getTransformer(xslt) out = ByteArrayOutputStream() reader = StringReader(xmlcontent) transformer.transform(StreamSource(reader),StreamResult(out)) return out
def loadContent(self, content): content = re.sub(self.NAMESPACE_PATTERN, '', content) # remove xml namespace reader = StringReader(content) self.__document = self.__builder.build(StreamSource(reader))
for (p, v) in parameters: transformer.setParameter(p, v) transformer.transform(source, result) args = sys.argv[1:] parameters = [] while args and args[0].startswith('-'): try: i = args[0].index('=') except ValueError: parameters.append((args[0], "")) else: parameters.append((args[0][1:i], args[0][i+1:])) args = args[1:] if len(args) == 1: source = StreamSource(System.in) elif len(args) >= 2: source = StreamSource(FileReader(args[1])) else: raise "Usage: <jython|wlst> transform.py -<parameter>=<value> <stylesheetfile> [inputfile] [outputfile]" if len(args) == 3: output = args[2] else: output = "" stylesheet = StreamSource(FileReader(args[0])) if len(output) == 0: result = StreamResult(PrintWriter(System.out)) else: result = StreamResult(FileWriter(File(output))) transform(source, stylesheet, result, parameters) stylesheet.reader.close() source.reader and source.reader.close()