1. /*
  2. * The Apache Software License, Version 1.1
  3. *
  4. *
  5. * Copyright (c) 1999 The Apache Software Foundation. All rights
  6. * reserved.
  7. *
  8. * Redistribution and use in source and binary forms, with or without
  9. * modification, are permitted provided that the following conditions
  10. * are met:
  11. *
  12. * 1. Redistributions of source code must retain the above copyright
  13. * notice, this list of conditions and the following disclaimer.
  14. *
  15. * 2. Redistributions in binary form must reproduce the above copyright
  16. * notice, this list of conditions and the following disclaimer in
  17. * the documentation and/or other materials provided with the
  18. * distribution.
  19. *
  20. * 3. The end-user documentation included with the redistribution,
  21. * if any, must include the following acknowledgment:
  22. * "This product includes software developed by the
  23. * Apache Software Foundation (http://www.apache.org/)."
  24. * Alternately, this acknowledgment may appear in the software itself,
  25. * if and wherever such third-party acknowledgments normally appear.
  26. *
  27. * 4. The names "Xalan" and "Apache Software Foundation" must
  28. * not be used to endorse or promote products derived from this
  29. * software without prior written permission. For written
  30. * permission, please contact apache@apache.org.
  31. *
  32. * 5. Products derived from this software may not be called "Apache",
  33. * nor may "Apache" appear in their name, without prior written
  34. * permission of the Apache Software Foundation.
  35. *
  36. * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
  37. * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  38. * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  39. * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
  40. * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  41. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  42. * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
  43. * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  44. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  45. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
  46. * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  47. * SUCH DAMAGE.
  48. * ====================================================================
  49. *
  50. * This software consists of voluntary contributions made by many
  51. * individuals on behalf of the Apache Software Foundation and was
  52. * originally based on software copyright (c) 1999, Lotus
  53. * Development Corporation., http://www.lotus.com. For more
  54. * information on the Apache Software Foundation, please see
  55. * <http://www.apache.org/>.
  56. */
  57. package org.apache.xalan.extensions;
  58. import java.util.Hashtable;
  59. import java.util.Vector;
  60. import java.lang.reflect.Method;
  61. import java.lang.reflect.Modifier;
  62. import java.lang.reflect.Constructor;
  63. import java.lang.reflect.InvocationTargetException;
  64. import java.io.IOException;
  65. //import org.w3c.dom.Element;
  66. //import org.w3c.dom.Node;
  67. import org.apache.xml.dtm.DTM;
  68. import org.apache.xalan.transformer.TransformerImpl;
  69. import org.apache.xalan.templates.Stylesheet;
  70. import org.apache.xalan.templates.ElemTemplateElement;
  71. import org.apache.xalan.res.XSLMessages;
  72. import org.apache.xalan.res.XSLTErrorResources;
  73. import org.apache.xml.utils.QName;
  74. import org.apache.xpath.objects.XObject;
  75. import javax.xml.transform.TransformerException;
  76. /**
  77. * <meta name="usage" content="internal"/>
  78. * Represents an extension namespace for XPath that handles java packages
  79. * that may be fully or partially specified.
  80. * It is recommended that the class URI be of one of the following forms:
  81. * <pre>
  82. * xalan://partial.class.name
  83. * xalan://
  84. * http://xml.apache.org/xalan/java (which is the same as xalan://)
  85. * </pre>
  86. * However, we do not enforce this. If the class name contains a
  87. * a /, we only use the part to the right of the rightmost slash.
  88. * In addition, we ignore any "class:" prefix.
  89. * Provides functions to test a function's existence and call a function.
  90. * Also provides functions to test an element's existence and call an
  91. * element.
  92. *
  93. * @author <a href="mailto:garyp@firstech.com">Gary L Peskin</a>
  94. *
  95. */
  96. public class ExtensionHandlerJavaPackage extends ExtensionHandlerJava
  97. {
  98. /**
  99. * Construct a new extension namespace handler given all the information
  100. * needed.
  101. *
  102. * @param namespaceUri the extension namespace URI that I'm implementing
  103. * @param scriptLang language of code implementing the extension
  104. * @param className the beginning of the class name of the class. This
  105. * should be followed by a dot (.)
  106. */
  107. public ExtensionHandlerJavaPackage(String namespaceUri,
  108. String scriptLang,
  109. String className)
  110. {
  111. super(namespaceUri, scriptLang, className);
  112. }
  113. /**
  114. * Tests whether a certain function name is known within this namespace.
  115. * Since this is for a package, we concatenate the package name used when
  116. * this handler was created and the function name specified in the argument.
  117. * There is
  118. * no information regarding the arguments to the function call or
  119. * whether the method implementing the function is a static method or
  120. * an instance method.
  121. * @param function name of the function being tested
  122. * @return true if its known, false if not.
  123. */
  124. public boolean isFunctionAvailable(String function)
  125. {
  126. try
  127. {
  128. String fullName = m_className + function;
  129. int lastDot = fullName.lastIndexOf(".");
  130. if (lastDot >= 0)
  131. {
  132. Class myClass = getClassForName(fullName.substring(0, lastDot));
  133. Method[] methods = myClass.getMethods();
  134. int nMethods = methods.length;
  135. function = fullName.substring(lastDot + 1);
  136. for (int i = 0; i < nMethods; i++)
  137. {
  138. if (methods[i].getName().equals(function))
  139. return true;
  140. }
  141. }
  142. }
  143. catch (ClassNotFoundException cnfe) {}
  144. return false;
  145. }
  146. /**
  147. * Tests whether a certain element name is known within this namespace.
  148. * Looks for a method with the appropriate name and signature.
  149. * This method examines both static and instance methods.
  150. * @param function name of the function being tested
  151. * @return true if its known, false if not.
  152. */
  153. public boolean isElementAvailable(String element)
  154. {
  155. try
  156. {
  157. String fullName = m_className + element;
  158. int lastDot = fullName.lastIndexOf(".");
  159. if (lastDot >= 0)
  160. {
  161. Class myClass = getClassForName(fullName.substring(0, lastDot));
  162. Method[] methods = myClass.getMethods();
  163. int nMethods = methods.length;
  164. element = fullName.substring(lastDot + 1);
  165. for (int i = 0; i < nMethods; i++)
  166. {
  167. if (methods[i].getName().equals(element))
  168. {
  169. Class[] paramTypes = methods[i].getParameterTypes();
  170. if ( (paramTypes.length == 2)
  171. && paramTypes[0].isAssignableFrom(
  172. org.apache.xalan.extensions.XSLProcessorContext.class)
  173. && paramTypes[1].isAssignableFrom(
  174. org.apache.xalan.templates.ElemExtensionCall.class) )
  175. {
  176. return true;
  177. }
  178. }
  179. }
  180. }
  181. }
  182. catch (ClassNotFoundException cnfe) {}
  183. return false;
  184. }
  185. /**
  186. * Process a call to a function in the package java namespace.
  187. * There are three possible types of calls:
  188. * <pre>
  189. * Constructor:
  190. * packagens:class.name.new(arg1, arg2, ...)
  191. *
  192. * Static method:
  193. * packagens:class.name.method(arg1, arg2, ...)
  194. *
  195. * Instance method:
  196. * packagens:method(obj, arg1, arg2, ...)
  197. * </pre>
  198. * We use the following rules to determine the type of call made:
  199. * <ol type="1">
  200. * <li>If the function name ends with a ".new", call the best constructor for
  201. * class whose name is formed by concatenating the value specified on
  202. * the namespace with the value specified in the function invocation
  203. * before ".new".</li>
  204. * <li>If the function name contains a period, call the best static method "method"
  205. * in the class whose name is formed by concatenating the value specified on
  206. * the namespace with the value specified in the function invocation.</li>
  207. * <li>Otherwise, call the best instance method "method"
  208. * in the class whose name is formed by concatenating the value specified on
  209. * the namespace with the value specified in the function invocation.
  210. * Note that a static method of the same
  211. * name will <i>not</i> be called in the current implementation. This
  212. * module does not verify that the obj argument is a member of the
  213. * package namespace.</li>
  214. * </ol>
  215. *
  216. * @param funcName Function name.
  217. * @param args The arguments of the function call.
  218. *
  219. * @return the return value of the function evaluation.
  220. *
  221. * @throws TransformerException if parsing trouble
  222. */
  223. public Object callFunction (String funcName,
  224. Vector args,
  225. Object methodKey,
  226. ExpressionContext exprContext)
  227. throws TransformerException
  228. {
  229. String className;
  230. String methodName;
  231. Class classObj;
  232. Object targetObject;
  233. int lastDot = funcName.lastIndexOf(".");
  234. Object[] methodArgs;
  235. Object[][] convertedArgs;
  236. Class[] paramTypes;
  237. try
  238. {
  239. if (funcName.endsWith(".new")) { // Handle constructor call
  240. methodArgs = new Object[args.size()];
  241. convertedArgs = new Object[1][];
  242. for (int i = 0; i < methodArgs.length; i++)
  243. {
  244. methodArgs[i] = args.elementAt(i);
  245. }
  246. Constructor c = (Constructor) getFromCache(methodKey, null, methodArgs);
  247. if (c != null)
  248. {
  249. try
  250. {
  251. paramTypes = c.getParameterTypes();
  252. MethodResolver.convertParams(methodArgs, convertedArgs, paramTypes, exprContext);
  253. return c.newInstance(convertedArgs[0]);
  254. }
  255. catch (InvocationTargetException ite)
  256. {
  257. throw ite;
  258. }
  259. catch(Exception e)
  260. {
  261. // Must not have been the right one
  262. }
  263. }
  264. className = m_className + funcName.substring(0, lastDot);
  265. try
  266. {
  267. classObj = getClassForName(className);
  268. }
  269. catch (ClassNotFoundException e)
  270. {
  271. throw new TransformerException(e);
  272. }
  273. c = MethodResolver.getConstructor(classObj,
  274. methodArgs,
  275. convertedArgs,
  276. exprContext);
  277. putToCache(methodKey, null, methodArgs, c);
  278. return c.newInstance(convertedArgs[0]);
  279. }
  280. else if (-1 != lastDot) { // Handle static method call
  281. methodArgs = new Object[args.size()];
  282. convertedArgs = new Object[1][];
  283. for (int i = 0; i < methodArgs.length; i++)
  284. {
  285. methodArgs[i] = args.elementAt(i);
  286. }
  287. Method m = (Method) getFromCache(methodKey, null, methodArgs);
  288. if (m != null)
  289. {
  290. try
  291. {
  292. paramTypes = m.getParameterTypes();
  293. MethodResolver.convertParams(methodArgs, convertedArgs, paramTypes, exprContext);
  294. return m.invoke(null, convertedArgs[0]);
  295. }
  296. catch (InvocationTargetException ite)
  297. {
  298. throw ite;
  299. }
  300. catch(Exception e)
  301. {
  302. // Must not have been the right one
  303. }
  304. }
  305. className = m_className + funcName.substring(0, lastDot);
  306. methodName = funcName.substring(lastDot + 1);
  307. try
  308. {
  309. classObj = getClassForName(className);
  310. }
  311. catch (ClassNotFoundException e)
  312. {
  313. throw new TransformerException(e);
  314. }
  315. m = MethodResolver.getMethod(classObj,
  316. methodName,
  317. methodArgs,
  318. convertedArgs,
  319. exprContext,
  320. MethodResolver.STATIC_ONLY);
  321. putToCache(methodKey, null, methodArgs, m);
  322. return m.invoke(null, convertedArgs[0]);
  323. }
  324. else { // Handle instance method call
  325. if (args.size() < 1)
  326. {
  327. throw new TransformerException(XSLMessages.createMessage(XSLTErrorResources.ER_INSTANCE_MTHD_CALL_REQUIRES, new Object[]{funcName })); //"Instance method call to method " + funcName
  328. //+ " requires an Object instance as first argument");
  329. }
  330. targetObject = args.elementAt(0);
  331. if (targetObject instanceof XObject) // Next level down for XObjects
  332. targetObject = ((XObject) targetObject).object();
  333. methodArgs = new Object[args.size() - 1];
  334. convertedArgs = new Object[1][];
  335. for (int i = 0; i < methodArgs.length; i++)
  336. {
  337. methodArgs[i] = args.elementAt(i+1);
  338. }
  339. Method m = (Method) getFromCache(methodKey, targetObject, methodArgs);
  340. if (m != null)
  341. {
  342. try
  343. {
  344. paramTypes = m.getParameterTypes();
  345. MethodResolver.convertParams(methodArgs, convertedArgs, paramTypes, exprContext);
  346. return m.invoke(targetObject, convertedArgs[0]);
  347. }
  348. catch (InvocationTargetException ite)
  349. {
  350. throw ite;
  351. }
  352. catch(Exception e)
  353. {
  354. // Must not have been the right one
  355. }
  356. }
  357. classObj = targetObject.getClass();
  358. m = MethodResolver.getMethod(classObj,
  359. funcName,
  360. methodArgs,
  361. convertedArgs,
  362. exprContext,
  363. MethodResolver.INSTANCE_ONLY);
  364. putToCache(methodKey, targetObject, methodArgs, m);
  365. return m.invoke(targetObject, convertedArgs[0]);
  366. }
  367. }
  368. catch (InvocationTargetException ite)
  369. {
  370. Throwable resultException = ite;
  371. Throwable targetException = ite.getTargetException();
  372. if (targetException instanceof TransformerException)
  373. throw ((TransformerException)targetException);
  374. else if (targetException != null)
  375. resultException = targetException;
  376. throw new TransformerException(resultException);
  377. }
  378. catch (Exception e)
  379. {
  380. // e.printStackTrace();
  381. throw new TransformerException(e);
  382. }
  383. }
  384. /**
  385. * Process a call to this extension namespace via an element. As a side
  386. * effect, the results are sent to the TransformerImpl's result tree.
  387. * For this namespace, only static element methods are currently supported.
  388. * If instance methods are needed, please let us know your requirements.
  389. * @param localPart Element name's local part.
  390. * @param element The extension element being processed.
  391. * @param transformer Handle to TransformerImpl.
  392. * @param stylesheetTree The compiled stylesheet tree.
  393. * @param mode The current mode.
  394. * @param sourceTree The root of the source tree (but don't assume
  395. * it's a Document).
  396. * @param sourceNode The current context node.
  397. * @param mode The current mode.
  398. * @param methodKey A key that uniquely identifies this element call.
  399. * @throws IOException if loading trouble
  400. * @throws TransformerException if parsing trouble
  401. */
  402. public void processElement (String localPart,
  403. ElemTemplateElement element,
  404. TransformerImpl transformer,
  405. Stylesheet stylesheetTree,
  406. Object methodKey)
  407. throws TransformerException, IOException
  408. {
  409. Object result = null;
  410. Class classObj;
  411. Method m = (Method) getFromCache(methodKey, null, null);
  412. if (null == m)
  413. {
  414. try
  415. {
  416. String fullName = m_className + localPart;
  417. int lastDot = fullName.lastIndexOf(".");
  418. if (lastDot < 0)
  419. throw new TransformerException(XSLMessages.createMessage(XSLTErrorResources.ER_INVALID_ELEMENT_NAME, new Object[]{fullName })); //"Invalid element name specified " + fullName);
  420. try
  421. {
  422. classObj = getClassForName(fullName.substring(0, lastDot));
  423. }
  424. catch (ClassNotFoundException e)
  425. {
  426. throw new TransformerException(e);
  427. }
  428. localPart = fullName.substring(lastDot + 1);
  429. m = MethodResolver.getElementMethod(classObj, localPart);
  430. if (!Modifier.isStatic(m.getModifiers()))
  431. throw new TransformerException(XSLMessages.createMessage(XSLTErrorResources.ER_ELEMENT_NAME_METHOD_STATIC, new Object[]{fullName })); //"Element name method must be static " + fullName);
  432. }
  433. catch (Exception e)
  434. {
  435. // e.printStackTrace ();
  436. throw new TransformerException (e);
  437. }
  438. putToCache(methodKey, null, null, m);
  439. }
  440. XSLProcessorContext xpc = new XSLProcessorContext(transformer,
  441. stylesheetTree);
  442. try
  443. {
  444. result = m.invoke(null, new Object[] {xpc, element});
  445. }
  446. catch (InvocationTargetException ite)
  447. {
  448. Throwable resultException = ite;
  449. Throwable targetException = ite.getTargetException();
  450. if (targetException instanceof TransformerException)
  451. throw ((TransformerException)targetException);
  452. else if (targetException != null)
  453. resultException = targetException;
  454. throw new TransformerException(resultException);
  455. }
  456. catch (Exception e)
  457. {
  458. // e.printStackTrace ();
  459. throw new TransformerException (e);
  460. }
  461. if (result != null)
  462. {
  463. xpc.outputToResultTree (stylesheetTree, result);
  464. }
  465. }
  466. }