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. */
  58. package org.apache.xml.utils.synthetic;
  59. import java.io.IOException;
  60. /**
  61. * <meta name="usage" content="internal"/>
  62. * This class supports invoking Java compilation from within
  63. * a Java program. Recent versions of the Java environment have
  64. * provided such an API (in tools.jar). But that isn't available
  65. * on all platforms, and a fallback to the command line may be needed
  66. * (though this too may not always be available, eg. for security
  67. * reasons).
  68. * <p>
  69. * There's an additional complication in some environments --
  70. * such as Microsoft's VJ++ -- where the classpath as seen in
  71. * the System Properties may not be the one the user expects.
  72. * The code here is parameterized to try to deal with that.
  73. */
  74. public class JavaUtils
  75. {
  76. // One-time flag for whether we could dynamically load compiler API
  77. private static boolean cantLoadCompiler=false;
  78. // Debug flag - generates debug stuff if true.
  79. private static boolean debug = false;
  80. /** Control whether compilation occurs with the -g option
  81. * (debugging information included in generated classfile).
  82. * This is an attribute, rather than a parameter on the compile
  83. * method, largely because it tends to be an all-or-nothing decision;
  84. * generally you're either doing program development and want it,
  85. * or running in production mode and don't. But that may not match
  86. * the needs of future users...
  87. * <p>
  88. * TODO: Consider whether debug should be a parameter.
  89. *
  90. * @param boolean newDebug True to request debugging data,
  91. * false to request optimized output. (It's uncommon to
  92. * want both or neither!)
  93. */
  94. public static void setDebug(boolean newDebug)
  95. {
  96. debug=newDebug;
  97. }
  98. /** Try to compile a .java file on disk. This will first attempt to
  99. * use the sun.java.tools.javac() method, then (if that is unavailable)
  100. * fall back upon shelling out to a command line and running javac
  101. * there.
  102. * <p>
  103. * NOTE: This must be _compiled_ with sun.java.tools.* (tools.jar)
  104. * available. We could change that to use reflection instead, if we
  105. * accept some overhead... minor compared to the cost of running the
  106. * compiler!
  107. * <p>
  108. * This has complications on some platforms. For example, under
  109. * Microsoft Visual Java ++ (at least, as installed on my test system),
  110. * I found that I had to specify paths to both javac and xerces.jar
  111. * rather than counting on the shell's path and classpath having
  112. * been set to reach these. For that reason I've parameterized this
  113. * method with a few system properties, so you can adapt it to your
  114. * own system's needs without modifying the code:
  115. * <dl>
  116. * <dt>org.apache.xml.utils.synthetic.javac
  117. * <dd>Command line issued to invoke the compiler. Defaults to "javac",
  118. * which should work in most systems. In VJ++, try setting it to
  119. * "cmd /c %JAVA_HOME%\\bin\javac.exe"
  120. * <dt>org.apache.xml.utils.synthetic.moreclasspath
  121. * <dd>Additional classpath, to be prepended to the one retrieved from
  122. * java.class.path. Defaults to "" (empty). In VJ++, try setting it to
  123. * point to your copy of xerces.jar, which may not be found otherwise.
  124. * TODO: Reconsider prepend versus append!
  125. * </dl>
  126. *
  127. * @param String fileName Which .java file to compile. Note that this may
  128. * be relative to the "current directory".
  129. * @param String classPath Additional places to look for classes that
  130. * this .java file depends upon. Becomes the javac command's
  131. * -classpath parameter value.
  132. * @return boolean True iff compilation succeeded.
  133. */
  134. public static boolean JDKcompile(String fileName, String classPath)
  135. {
  136. String moreClassPath=
  137. System.getProperty("org.apache.xml.utils.synthetic.moreclasspath","")
  138. .trim();
  139. if(moreClassPath.length()>0)
  140. classPath=moreClassPath+';'+classPath;
  141. if (debug)
  142. {
  143. System.err.println ("JavaEngine: Compiling " + fileName);
  144. System.err.println ("JavaEngine: Classpath is " + classPath);
  145. }
  146. String code_option = debug ? "-g" : "-O";
  147. // Start by trying Sun's compiler API
  148. if(!cantLoadCompiler)
  149. {
  150. String args[] = {
  151. code_option,
  152. "-classpath", classPath,
  153. fileName
  154. };
  155. // try
  156. // {
  157. // return new sun.tools.javac.Main(System.err, "javac").compile(args);
  158. // }
  159. // catch (Throwable th)
  160. // {
  161. // System.err.println("INFORMATIONAL: Unable to load Java compiler API (eg tools.jar).");
  162. // System.err.println("\tSwitching to command-line invocation.");
  163. // cantLoadCompiler=true;
  164. // }
  165. }
  166. // FALLTHRU:
  167. // Can't load javac() method; try shelling out to the command
  168. // line and invoking it via exec().
  169. String javac_command=
  170. System.getProperty("org.apache.xml.utils.synthetic.javac","javac");
  171. String args[] = {
  172. javac_command,
  173. code_option,
  174. "-classpath", classPath,
  175. fileName
  176. };
  177. try
  178. {
  179. Process p=java.lang.Runtime.getRuntime().exec(args);
  180. int compileOK=waitHardFor(p); // pause for debugging...
  181. return compileOK==0; //0 == no error reported
  182. }
  183. catch(IOException e)
  184. {
  185. System.err.println("ERROR: IO exception during exec(javac).");
  186. }
  187. catch(SecurityException e)
  188. {
  189. System.err.println("ERROR: Unable to create subprocess to exec(javac).");
  190. }
  191. // FALLTHRU: All attempts failed.
  192. return false;
  193. }
  194. /** Subroutine: Like p.waitFor, but discards the InterruptedException
  195. * and goes right back into a wait. I don't want to report compiler
  196. * success or failure until it really has succeeded or failed... I think.
  197. * @param Process p to be waited for
  198. * @return the exitValue() of the process.
  199. */
  200. static int waitHardFor(java.lang.Process p)
  201. {
  202. boolean done=false;
  203. while(!done)
  204. try
  205. {
  206. p.waitFor();
  207. done=true;
  208. }
  209. catch(InterruptedException e)
  210. {
  211. System.err.println("(Compiler process wait interrupted and resumed)");
  212. }
  213. int ev=p.exitValue(); // Pause for debugging...
  214. return ev;
  215. }
  216. }