xslprocessor.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682
  1. /*##############################################################################
  2. Copyright (C) 2011 HPCC Systems.
  3. All rights reserved. This program is free software: you can redistribute it and/or modify
  4. it under the terms of the GNU Affero General Public License as
  5. published by the Free Software Foundation, either version 3 of the
  6. License, or (at your option) any later version.
  7. This program is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU Affero General Public License for more details.
  11. You should have received a copy of the GNU Affero General Public License
  12. along with this program. If not, see <http://www.gnu.org/licenses/>.
  13. ############################################################################## */
  14. #include "xslprocessor.ipp"
  15. #include "jencrypt.hpp"
  16. #include "jexcept.hpp"
  17. #include "xalanc/XPath/XObjectFactory.hpp"
  18. #include "xalanc/PlatformSupport/Writer.hpp"
  19. /*
  20. class StringBufferOStreamBuf : public std::basic_streambuf<char, std::char_traits<char> >
  21. {
  22. StringBuffer & _inputbuffer;
  23. typedef std::char_traits<char> _Tr;
  24. protected:
  25. virtual int overflow(int = _Tr::eof());
  26. public:
  27. StringBufferOStreamBuf(StringBuffer &_str);
  28. };
  29. StringBufferOStreamBuf::StringBufferOStreamBuf(StringBuffer &_str) : _inputbuffer(_str)
  30. {
  31. }
  32. int StringBufferOStreamBuf::overflow(int c)
  33. {
  34. if(c == _Tr::eof()) return _Tr::not_eof(c);
  35. _inputbuffer.append((char) c);
  36. return c;
  37. }
  38. class StringBufferOStream : public std::basic_ostream<char, std::char_traits<char> >
  39. {
  40. StringBufferOStreamBuf _streambuffer;
  41. public:
  42. StringBufferOStream(StringBuffer &buf)
  43. : _streambuffer(buf),
  44. std::basic_ostream<char, std::char_traits<char> >(&_streambuffer)
  45. { clear(); }
  46. };
  47. */
  48. //-------------------------------------------------
  49. XALAN_USING_XALAN(Writer)
  50. XALAN_USING_XALAN(XalanOutputStream)
  51. XALAN_USING_XALAN(XalanDOMChar)
  52. class ISocketOutputStream : public IInterface
  53. {
  54. public:
  55. virtual Writer* getWriter() = 0;
  56. };
  57. //XALAN_CPP_NAMESPACE_BEGIN
  58. class SocketOutputStream : public CInterface, public ISocketOutputStream, public Writer
  59. {
  60. private:
  61. ISocket *m_socket;
  62. public:
  63. IMPLEMENT_IINTERFACE;
  64. SocketOutputStream(ISocket *s);
  65. ~SocketOutputStream() { close(); }
  66. virtual Writer* getWriter() { return this; }
  67. // Close the stream
  68. virtual void close();
  69. // Flush the stream
  70. virtual void flush();
  71. // Get the stream associated with the writer...
  72. virtual XalanOutputStream* getStream();
  73. // Get the stream associated with the writer...
  74. virtual const XalanOutputStream* getStream() const;
  75. // Writes a string
  76. virtual void write(const char* s, size_t theOffset = 0, size_t theLength = ~0u);
  77. // Writes a string
  78. virtual void write(const XalanDOMChar* s, XalanDOMString::size_type theOffset=0,
  79. XalanDOMString::size_type theLength = XalanDOMString::npos);
  80. // Writes a character
  81. virtual void write(XalanDOMChar c);
  82. // Writes a string
  83. virtual void write(const XalanDOMString& s, XalanDOMString::size_type theOffset = 0,
  84. XalanDOMString::size_type theLength = XalanDOMString::npos);
  85. };
  86. SocketOutputStream::SocketOutputStream(ISocket* s)
  87. {
  88. m_socket = s;
  89. }
  90. void SocketOutputStream::close()
  91. {
  92. //fprintf(stderr,"close()\n");
  93. //m_socket->shutdown();
  94. //m_socket->close();
  95. }
  96. void SocketOutputStream::flush()
  97. {
  98. //fprintf(stderr,"flush()\n");
  99. }
  100. XalanOutputStream* SocketOutputStream::getStream()
  101. {
  102. fprintf(stderr, "Unsupported getStream()!");
  103. return NULL;
  104. }
  105. const XalanOutputStream* SocketOutputStream::getStream() const
  106. {
  107. fprintf(stderr, "Unsupported getStream()!");
  108. return NULL;
  109. }
  110. void SocketOutputStream::write(const char* s, size_t offset, size_t length)
  111. {
  112. //wprintf(stderr,TEXT("write(char*='%s',offset=%d,length=%d)\n"),s,offset,length);
  113. m_socket->write(s + offset, length);
  114. }
  115. //XalanDOMChar: utf-8 or wchar_t
  116. void SocketOutputStream::write(const XalanDOMChar* s, XalanDOMString::size_type offset,
  117. XalanDOMString::size_type length)
  118. {
  119. //printf(stderr,"write(DOMChar='%s',offset=%d,length=%d)\n",s,offset,length);
  120. m_socket->write((const char* )(s+offset), length * sizeof(XalanDOMChar));
  121. }
  122. void SocketOutputStream::write(XalanDOMChar c)
  123. {
  124. //printf(stderr, "write(%c)", c);
  125. m_socket->write((const char*)&c, sizeof(XalanDOMChar));
  126. }
  127. void SocketOutputStream::write(const XalanDOMString& s, XalanDOMString::size_type offset,
  128. XalanDOMString::size_type length)
  129. {
  130. //printf(stderr,"write(DOMString='%s',offset=%d,length=%s", s.c_str(), offset, length);
  131. m_socket->write((const char*)(s.c_str()+offset), length*sizeof(XalanDOMChar));
  132. }
  133. extern ISocketOutputStream* createSocketOutputStream(ISocket* s)
  134. {
  135. return new SocketOutputStream(s);
  136. }
  137. //-------------------------------------------------
  138. class XalanStringBufferOutputHandler
  139. {
  140. StringBuffer & _inputbuffer;
  141. public:
  142. XalanStringBufferOutputHandler(StringBuffer &_str) : _inputbuffer(_str)
  143. {
  144. }
  145. static unsigned long callback(const char *data, unsigned long len, void *ctx)
  146. {
  147. XalanStringBufferOutputHandler *self = (XalanStringBufferOutputHandler *) ctx;
  148. self->_inputbuffer.append(len, data);
  149. return len;
  150. }
  151. };
  152. //----------------------------------------------------------------------------
  153. // CExternalFunction
  154. //----------------------------------------------------------------------------
  155. XObjectPtr CExternalFunction::execute( XPathExecutionContext& executionContext,
  156. XalanNode* /* context */,
  157. const XObjectPtr arg1,
  158. const Locator* /* locator */) const
  159. {
  160. assert(arg1.null() == false);
  161. const XalanDOMString& arg = arg1->str();
  162. //convert XalanDOMString (implemented as unsigned short*) into StringBuffer
  163. StringBuffer sbInput;
  164. sbInput.ensureCapacity(arg.length()+1);
  165. size32_t len = arg.length();
  166. for (int i=0; i < len; i++)
  167. sbInput.append( (char) arg[i]);
  168. StringBuffer sbOutput;
  169. try
  170. {
  171. (*m_userFunction)(sbOutput, sbInput.str(), m_pTransform);
  172. }
  173. catch (IException* e)
  174. {
  175. StringBuffer msg;
  176. e->errorMessage(msg);
  177. e->Release();
  178. }
  179. catch (...)
  180. {
  181. }
  182. XalanDOMString xdsOutput( sbOutput.str() );
  183. return executionContext.getXObjectFactory().createString( xdsOutput );
  184. }
  185. //----------------------------------------------------------------------------
  186. // CXslProcessor
  187. //----------------------------------------------------------------------------
  188. extern IXslProcessor* getXslProcessor()
  189. {
  190. static CXslProcessor s_pXslProcessor;
  191. return LINK(&s_pXslProcessor);
  192. }
  193. // Should be called only once per-process
  194. class XslProcessorInitializer
  195. {
  196. public:
  197. XslProcessorInitializer()
  198. {
  199. // Call the static initializer for Xerces.
  200. XMLPlatformUtils::Initialize();
  201. // Initialize Xalan.
  202. XalanTransformer::initialize();
  203. }
  204. ~XslProcessorInitializer()
  205. {
  206. // Terminate Xalan.
  207. XalanTransformer::terminate();
  208. // Call the static terminator for Xerces.
  209. XMLPlatformUtils::Terminate();
  210. }
  211. };
  212. CXslProcessor::CXslProcessor()
  213. {
  214. static XslProcessorInitializer initializer;
  215. m_cachetimeout = XSLT_DEFAULT_CACHETIMEOUT;
  216. }
  217. // Should be called only once per-process
  218. CXslProcessor::~CXslProcessor()
  219. {
  220. }
  221. IXslTransform *CXslProcessor::createXslTransform()
  222. {
  223. return new CXslTransform(inch.get());
  224. }
  225. int CXslProcessor::execute(IXslTransform *pITransform)
  226. {
  227. return ((CXslTransform*)pITransform)->transform();
  228. }
  229. void CXslProcessor::setCacheTimeout(int timeout)
  230. {
  231. m_cachetimeout = timeout;
  232. IXslCache* xslcache = getXslCache();
  233. if(xslcache)
  234. xslcache->setCacheTimeout(timeout);
  235. }
  236. int CXslProcessor::getCacheTimeout()
  237. {
  238. return m_cachetimeout;
  239. }
  240. //----------------------------------------------------------------------------
  241. // CXslTransform
  242. //----------------------------------------------------------------------------
  243. /*static*/ const char* CXslTransform::SEISINT_NAMESPACE = "http://seisint.com";
  244. CXslTransform::CXslTransform(IIncludeHandler* handler) : m_XalanTransformer()
  245. {
  246. m_ParsedSource = 0;
  247. m_resultTarget = 0;
  248. m_ostrstream = 0;
  249. m_sourceResolver = NULL;
  250. m_pUserData = NULL;
  251. #ifdef _WIN32
  252. m_normalizeLinefeed = true; //default for Xalan
  253. #endif
  254. if (handler)
  255. setIncludeHandler(handler);
  256. //set an external function to handle non-fatal XSL messages
  257. m_fnMessage.setown(createExternalFunction("message", message));
  258. setExternalFunction(SEISINT_NAMESPACE, m_fnMessage.get(), true);
  259. }
  260. CXslTransform::~CXslTransform()
  261. {
  262. setExternalFunction(SEISINT_NAMESPACE, m_fnMessage.get(), false);
  263. if(m_sourceResolver != NULL)
  264. delete m_sourceResolver;
  265. if(m_ParsedSource)
  266. {
  267. m_XalanTransformer.destroyParsedSource(m_ParsedSource);
  268. m_ParsedSource = NULL;
  269. }
  270. closeResultTarget();
  271. }
  272. bool CXslTransform::checkSanity()
  273. {
  274. return (m_xslsource && m_ParsedSource);
  275. }
  276. int CXslTransform::transform(StringBuffer &target)
  277. {
  278. if(!m_ParsedSource)
  279. throw MakeStringException(1, "[XML source not set]");
  280. else if(!m_xslsource)
  281. throw MakeStringException(2, "[XSL stylesheet not set]");
  282. XalanCompiledStylesheet* pCompiledStylesheet = NULL;
  283. const bool bReloadStylesheet = false;
  284. pCompiledStylesheet = m_xslsource->getStylesheet(bReloadStylesheet);
  285. if (!pCompiledStylesheet)
  286. {
  287. DBGLOG("[failed to compile XSLT stylesheet]");
  288. throw MakeStringException(2, "[failed to compile XSLT stylesheet]");
  289. }
  290. int rc=0;
  291. m_sMessages.clear();
  292. try
  293. {
  294. XalanStringBufferOutputHandler output(target);
  295. rc = m_XalanTransformer.transform(*m_ParsedSource, pCompiledStylesheet,
  296. (void*)&output, (XalanOutputHandlerType)output.callback, (XalanFlushHandlerType)0);
  297. }
  298. catch(...)
  299. {
  300. StringBuffer estr("[Exception running XSLT stylesheet]");
  301. estr.appendf("[%s]", m_XalanTransformer.getLastError());
  302. DBGLOG("%s", estr.str());
  303. throw MakeStringException(2, "%s", estr.str());
  304. }
  305. if (rc < 0)
  306. {
  307. StringBuffer estr;
  308. estr.appendf("[%s]", m_XalanTransformer.getLastError());
  309. DBGLOG("%s", estr.str());
  310. throw MakeStringException(2, "%s", estr.str());
  311. }
  312. return rc;
  313. }
  314. int CXslTransform::transform()
  315. {
  316. if(!m_ParsedSource)
  317. throw MakeStringException(1, "[XML source not set for XSLT[");
  318. else if(!m_xslsource)
  319. throw MakeStringException(2, "[XSL stylesheet not set]");
  320. else if(!m_resultTarget)
  321. throw MakeStringException(2, "[XSLT target file/buffer not set]");
  322. XalanCompiledStylesheet* pCompiledStylesheet = NULL;
  323. const bool bReloadStylesheet = false;
  324. pCompiledStylesheet = m_xslsource->getStylesheet(bReloadStylesheet);
  325. if (!pCompiledStylesheet)
  326. {
  327. DBGLOG("[failed to compile XSLT stylesheet]");
  328. throw MakeStringException(2, "[failed to compile XSLT stylesheet]");
  329. }
  330. int rc=0;
  331. m_sMessages.clear();
  332. try
  333. {
  334. rc = m_XalanTransformer.transform(*m_ParsedSource, pCompiledStylesheet, *m_resultTarget);
  335. }
  336. catch(...)
  337. {
  338. StringBuffer estr("[Exception running XSLT stylesheet]");
  339. estr.appendf("[%s]", m_XalanTransformer.getLastError());
  340. DBGLOG("%s", estr.str());
  341. throw MakeStringException(2, "%s", estr.str());
  342. }
  343. if (rc < 0)
  344. {
  345. StringBuffer estr;
  346. estr.appendf("[%s]", m_XalanTransformer.getLastError());
  347. DBGLOG("%s", estr.str());
  348. throw MakeStringException(2, "%s", estr.str());
  349. }
  350. return rc;
  351. }
  352. int CXslTransform::transform(ISocket* targetSocket)
  353. {
  354. if(!m_ParsedSource)
  355. throw MakeStringException(1, "[XML source not set for XSLT[");
  356. else if(!m_xslsource)
  357. throw MakeStringException(2, "[XSL stylesheet not set]");
  358. XalanCompiledStylesheet* pCompiledStylesheet = NULL;
  359. const bool bReloadStylesheet = false;
  360. pCompiledStylesheet = m_xslsource->getStylesheet(bReloadStylesheet);
  361. if (!pCompiledStylesheet)
  362. {
  363. DBGLOG("[failed to compile XSLT stylesheet]");
  364. throw MakeStringException(2, "[failed to compile XSLT stylesheet]");
  365. }
  366. int rc=0;
  367. m_sMessages.clear();
  368. try
  369. {
  370. m_resultTarget = new XSLTResultTarget();
  371. Owned<ISocketOutputStream> stream = createSocketOutputStream(targetSocket);
  372. m_resultTarget->setCharacterStream(stream->getWriter());
  373. rc = m_XalanTransformer.transform(*m_ParsedSource, pCompiledStylesheet, *m_resultTarget);
  374. }
  375. catch(...)
  376. {
  377. StringBuffer estr("[Exception running XSLT stylesheet]");
  378. estr.appendf("[%s]", m_XalanTransformer.getLastError());
  379. DBGLOG("%s", estr.str());
  380. throw MakeStringException(2, "%s", estr.str());
  381. }
  382. if (rc < 0)
  383. {
  384. StringBuffer estr;
  385. estr.appendf("[%s]", m_XalanTransformer.getLastError());
  386. DBGLOG("%s", estr.str());
  387. throw MakeStringException(2, "%s", estr.str());
  388. }
  389. return rc;
  390. }
  391. int CXslTransform::setXmlSource(const char *pszFileName)
  392. {
  393. if(m_ParsedSource != NULL)
  394. {
  395. m_XalanTransformer.destroyParsedSource(m_ParsedSource);
  396. m_ParsedSource = NULL;
  397. }
  398. int theResult = 0;
  399. try
  400. {
  401. std::ifstream theXMLStream(pszFileName);
  402. const XSLTInputSource xmlinput(&theXMLStream);
  403. theResult = m_XalanTransformer.parseSource(xmlinput, (const XalanParsedSource*&)m_ParsedSource);
  404. }
  405. catch(...)
  406. {
  407. m_ParsedSource = NULL;
  408. StringBuffer estr("[Exception compiling xml]");
  409. estr.appendf("[%s]", m_XalanTransformer.getLastError());
  410. DBGLOG("%s", estr.str());
  411. throw MakeStringException(2, "%s", estr.str());
  412. }
  413. if (!m_ParsedSource)
  414. {
  415. StringBuffer estr("[failed to compile xml]");
  416. estr.appendf("[%s]", m_XalanTransformer.getLastError());
  417. DBGLOG("%s", estr.str());
  418. throw MakeStringException(2, "%s", estr.str());
  419. }
  420. return theResult;
  421. }
  422. int CXslTransform::setXmlSource(const char *pszBuffer, unsigned int nSize)
  423. {
  424. if(m_ParsedSource != NULL)
  425. {
  426. m_XalanTransformer.destroyParsedSource(m_ParsedSource);
  427. m_ParsedSource = NULL;
  428. }
  429. int theResult = 0;
  430. try
  431. {
  432. //std::istringstream theXMLStream(pszBuffer, nSize);
  433. std::istringstream theXMLStream(pszBuffer);
  434. const XSLTInputSource xmlinput(&theXMLStream);
  435. theResult = m_XalanTransformer.parseSource(xmlinput, (const XalanParsedSource*&)m_ParsedSource);
  436. }
  437. catch(...)
  438. {
  439. m_ParsedSource = NULL;
  440. StringBuffer estr("[Exception compiling xml]");
  441. estr.appendf("[%s]", m_XalanTransformer.getLastError());
  442. DBGLOG("%s", estr.str());
  443. throw MakeStringException(2, "%s", estr.str());
  444. }
  445. if (!m_ParsedSource)
  446. {
  447. StringBuffer estr("[failed to compile xml]");
  448. estr.appendf("[%s]", m_XalanTransformer.getLastError());
  449. DBGLOG("%s", estr.str());
  450. throw MakeStringException(2, "%s", estr.str());
  451. }
  452. return theResult;
  453. }
  454. int CXslTransform::setXslSource(const char *pszFileName)
  455. {
  456. m_xslsource.setown(new CXslSource(pszFileName, m_sourceResolver?m_sourceResolver->getIncludeHandler():NULL));
  457. return 0;
  458. }
  459. int CXslTransform::setXslSource(const char *pszBuffer, unsigned int nSize, const char *rootpath)
  460. {
  461. m_xslsource.setown(new CXslSource(pszBuffer, nSize, m_sourceResolver?m_sourceResolver->getIncludeHandler():NULL, rootpath));
  462. return 0;
  463. }
  464. int CXslTransform::setResultTarget(const char *pszFileName)
  465. {
  466. closeResultTarget();
  467. try
  468. {
  469. m_resultTargetFile.clear().append(pszFileName);
  470. m_resultTarget = new XSLTResultTarget(XalanDOMString(pszFileName));
  471. }
  472. catch(...)
  473. {
  474. throw MakeStringException(1, "Exception opening file %s", pszFileName);
  475. }
  476. return 0;
  477. }
  478. int CXslTransform::setResultTarget(char *pszBuffer, unsigned int nSize)
  479. {
  480. closeResultTarget();
  481. // Our output target that uses an ostrstream that will use the buffer
  482. try
  483. {
  484. //m_ostrstream = new std::ostringstream(pszBuffer, nSize);
  485. m_ostrstream = new std::ostringstream(pszBuffer);
  486. m_resultTarget = new XSLTResultTarget(m_ostrstream);
  487. }
  488. catch(...)
  489. {
  490. throw MakeStringException(1, "Exception in setting character buffer as XSLT result target.");
  491. }
  492. return 0;
  493. }
  494. int CXslTransform::closeResultTarget()
  495. {
  496. if (m_resultTarget)
  497. {
  498. delete m_resultTarget;
  499. m_resultTarget = 0;
  500. }
  501. if(m_ostrstream)
  502. {
  503. delete m_ostrstream;
  504. m_ostrstream = 0;
  505. }
  506. return 0;
  507. }
  508. int CXslTransform::setParameter(const char *pszName, const char *pszExpression)
  509. {
  510. m_XalanTransformer.setStylesheetParam(XalanDOMString(pszName), XalanDOMString(pszExpression));
  511. return 0;
  512. }
  513. int CXslTransform::setStringParameter(const char *pszName, const char *pszString)
  514. {
  515. m_XalanTransformer.setStylesheetParam(XalanDOMString(pszName), XalanDOMString(StringBuffer("'").append(pszString).append("'").str()));
  516. return 0;
  517. }
  518. int CXslTransform::setIncludeHandler(IIncludeHandler* handler)
  519. {
  520. if(handler == NULL)
  521. {
  522. throw MakeStringException(-1, "From CXslTransform::setIncludeHandler: a NULL handler is passed in");
  523. }
  524. if(m_sourceResolver == NULL)
  525. {
  526. m_sourceResolver = new MemSourceResolver();
  527. }
  528. m_sourceResolver->setHandler(handler);
  529. m_XalanTransformer.setEntityResolver(m_sourceResolver);
  530. if(m_xslsource.get() != NULL)
  531. {
  532. m_xslsource->setIncludeHandler(handler);
  533. }
  534. return 0;
  535. }
  536. int CXslTransform::setExternalFunction(const char* pszNameSpace, IXslFunction* pXslFunction, bool set)
  537. {
  538. CXslFunction* pFn = (CXslFunction*) pXslFunction;
  539. if (pFn == NULL || pFn->get() == NULL)
  540. throw MakeStringException(-1, "Null pointer violation in CXslTransform::setExternalFunction.");
  541. XalanDOMString nameSpace(pszNameSpace);
  542. XalanDOMString functionName(pFn->getName());
  543. bool bAssigned = pFn->isAssigned();
  544. if (set && !bAssigned)
  545. m_XalanTransformer.installExternalFunction(nameSpace, functionName, *pFn->get());
  546. else
  547. {
  548. if (!set && bAssigned)
  549. m_XalanTransformer.uninstallExternalFunction(nameSpace, functionName);
  550. else
  551. throw MakeStringException(-1, "XSLT external function assignment error!");
  552. }
  553. pFn->setAssigned(set);
  554. return 0;
  555. }
  556. /*static*/
  557. void CXslTransform::message(StringBuffer& out, const char* in, IXslTransform* pTransform)
  558. {
  559. CXslTransform* pTrans = dynamic_cast<CXslTransform*>(pTransform);
  560. pTrans->m_sMessages.append(in).append('\n');
  561. }