1. /*
  2. * Copyright 2000-2004 The Apache Software Foundation
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. *
  16. */
  17. package org.apache.tools.ant.taskdefs;
  18. import java.io.File;
  19. import java.io.IOException;
  20. import java.rmi.Remote;
  21. import java.util.Vector;
  22. import org.apache.tools.ant.BuildException;
  23. import org.apache.tools.ant.DirectoryScanner;
  24. import org.apache.tools.ant.Project;
  25. import org.apache.tools.ant.taskdefs.rmic.RmicAdapter;
  26. import org.apache.tools.ant.taskdefs.rmic.RmicAdapterFactory;
  27. import org.apache.tools.ant.types.FilterSetCollection;
  28. import org.apache.tools.ant.types.Path;
  29. import org.apache.tools.ant.types.Reference;
  30. import org.apache.tools.ant.util.FileNameMapper;
  31. import org.apache.tools.ant.util.FileUtils;
  32. import org.apache.tools.ant.util.SourceFileScanner;
  33. import org.apache.tools.ant.util.facade.FacadeTaskHelper;
  34. /**
  35. * Runs the rmic compiler against classes.</p>
  36. * <p>Rmic can be run on a single class (as specified with the classname
  37. * attribute) or a number of classes at once (all classes below base that
  38. * are neither _Stub nor _Skel classes). If you want to rmic a single
  39. * class and this class is a class nested into another class, you have to
  40. * specify the classname in the form <code>Outer$$Inner</code> instead of
  41. * <code>Outer.Inner</code>.</p>
  42. * <p>It is possible to refine the set of files that are being rmiced. This can
  43. * be done with the <i>includes</i>, <i>includesfile</i>, <i>excludes</i>,
  44. * <i>excludesfile</i> and <i>defaultexcludes</i>
  45. * attributes. With the <i>includes</i> or <i>includesfile</i> attribute you
  46. * specify the files you want to have included by using patterns. The
  47. * <i>exclude</i> or <i>excludesfile</i> attribute is used to specify
  48. * the files you want to have excluded. This is also done with patterns. And
  49. * finally with the <i>defaultexcludes</i> attribute, you can specify whether
  50. * you want to use default exclusions or not. See the section on
  51. * directory based tasks</a>, on how the
  52. * inclusion/exclusion of files works, and how to write patterns.</p>
  53. * <p>This task forms an implicit FileSet and
  54. * supports all attributes of <code><fileset></code>
  55. * (<code>dir</code> becomes <code>base</code>) as well as the nested
  56. * <code><include></code>, <code><exclude></code> and
  57. * <code><patternset></code> elements.</p>
  58. * <p>It is possible to use different compilers. This can be selected
  59. * with the "build.rmic" property or the <code>compiler</code>
  60. * attribute. <a name="compilervalues">There are three choices</a>:</p>
  61. * <ul>
  62. * <li>sun (the standard compiler of the JDK)</li>
  63. * <li>kaffe (the standard compiler of
  64. * {@link <a href="http://www.kaffe.org">Kaffe</a>})</li>
  65. * <li>weblogic</li>
  66. * </ul>
  67. *
  68. * <p> The <a href="http://dione.zcu.cz/~toman40/miniRMI/">miniRMI</a>
  69. * project contains a compiler implementation for this task as well,
  70. * please consult miniRMI's documentation to learn how to use it.</p>
  71. *
  72. *
  73. * @since Ant 1.1
  74. *
  75. * @ant.task category="java"
  76. */
  77. public class Rmic extends MatchingTask {
  78. private static final String FAIL_MSG
  79. = "Rmic failed; see the compiler error output for details.";
  80. private File baseDir;
  81. private String classname;
  82. private File sourceBase;
  83. private String stubVersion;
  84. private Path compileClasspath;
  85. private Path extdirs;
  86. private boolean verify = false;
  87. private boolean filtering = false;
  88. private boolean iiop = false;
  89. private String iiopopts;
  90. private boolean idl = false;
  91. private String idlopts;
  92. private boolean debug = false;
  93. private boolean includeAntRuntime = true;
  94. private boolean includeJavaRuntime = false;
  95. private Vector compileList = new Vector();
  96. private ClassLoader loader = null;
  97. private FileUtils fileUtils = FileUtils.newFileUtils();
  98. private FacadeTaskHelper facade;
  99. public Rmic() {
  100. try {
  101. Class.forName("kaffe.rmi.rmic.RMIC");
  102. facade = new FacadeTaskHelper("kaffe");
  103. } catch (ClassNotFoundException cnfe) {
  104. facade = new FacadeTaskHelper("sun");
  105. }
  106. }
  107. /**
  108. * Sets the location to store the compiled files; required
  109. */
  110. public void setBase(File base) {
  111. this.baseDir = base;
  112. }
  113. /**
  114. * Gets the base directory to output generated class.
  115. */
  116. public File getBase() {
  117. return this.baseDir;
  118. }
  119. /**
  120. * Sets the class to run <code>rmic</code> against;
  121. * optional
  122. */
  123. public void setClassname(String classname) {
  124. this.classname = classname;
  125. }
  126. /**
  127. * Gets the class name to compile.
  128. */
  129. public String getClassname() {
  130. return classname;
  131. }
  132. /**
  133. * optional directory to save generated source files to.
  134. */
  135. public void setSourceBase(File sourceBase) {
  136. this.sourceBase = sourceBase;
  137. }
  138. /**
  139. * Gets the source dirs to find the source java files.
  140. */
  141. public File getSourceBase() {
  142. return sourceBase;
  143. }
  144. /**
  145. * Specify the JDK version for the generated stub code.
  146. * Specify "1.1" to pass the "-v1.1" option to rmic.</td>
  147. */
  148. public void setStubVersion(String stubVersion) {
  149. this.stubVersion = stubVersion;
  150. }
  151. public String getStubVersion() {
  152. return stubVersion;
  153. }
  154. /**
  155. * indicates whether token filtering should take place;
  156. * optional, default=false
  157. */
  158. public void setFiltering(boolean filter) {
  159. filtering = filter;
  160. }
  161. public boolean getFiltering() {
  162. return filtering;
  163. }
  164. /**
  165. * generate debug info (passes -g to rmic);
  166. * optional, defaults to false
  167. */
  168. public void setDebug(boolean debug) {
  169. this.debug = debug;
  170. }
  171. /**
  172. * Gets the debug flag.
  173. */
  174. public boolean getDebug() {
  175. return debug;
  176. }
  177. /**
  178. * Set the classpath to be used for this compilation.
  179. */
  180. public void setClasspath(Path classpath) {
  181. if (compileClasspath == null) {
  182. compileClasspath = classpath;
  183. } else {
  184. compileClasspath.append(classpath);
  185. }
  186. }
  187. /**
  188. * Creates a nested classpath element.
  189. */
  190. public Path createClasspath() {
  191. if (compileClasspath == null) {
  192. compileClasspath = new Path(getProject());
  193. }
  194. return compileClasspath.createPath();
  195. }
  196. /**
  197. * Adds to the classpath a reference to
  198. * a <path> defined elsewhere.
  199. */
  200. public void setClasspathRef(Reference r) {
  201. createClasspath().setRefid(r);
  202. }
  203. /**
  204. * Gets the classpath.
  205. */
  206. public Path getClasspath() {
  207. return compileClasspath;
  208. }
  209. /**
  210. * Flag to enable verification so that the classes
  211. * found by the directory match are
  212. * checked to see if they implement java.rmi.Remote.
  213. * Optional; his defaults to false if not set.
  214. */
  215. public void setVerify(boolean verify) {
  216. this.verify = verify;
  217. }
  218. /** Get verify flag. */
  219. public boolean getVerify() {
  220. return verify;
  221. }
  222. /**
  223. * Indicates that IIOP compatible stubs should
  224. * be generated; optional, defaults to false
  225. * if not set.
  226. */
  227. public void setIiop(boolean iiop) {
  228. this.iiop = iiop;
  229. }
  230. /**
  231. * Gets iiop flags.
  232. */
  233. public boolean getIiop() {
  234. return iiop;
  235. }
  236. /**
  237. * Set additional arguments for iiop
  238. */
  239. public void setIiopopts(String iiopopts) {
  240. this.iiopopts = iiopopts;
  241. }
  242. /**
  243. * Gets additional arguments for iiop.
  244. */
  245. public String getIiopopts() {
  246. return iiopopts;
  247. }
  248. /**
  249. * Indicates that IDL output should be
  250. * generated. This defaults to false
  251. * if not set.
  252. */
  253. public void setIdl(boolean idl) {
  254. this.idl = idl;
  255. }
  256. /**
  257. * Gets IDL flags.
  258. */
  259. public boolean getIdl() {
  260. return idl;
  261. }
  262. /**
  263. * pass additional arguments for idl compile
  264. */
  265. public void setIdlopts(String idlopts) {
  266. this.idlopts = idlopts;
  267. }
  268. /**
  269. * Gets additional arguments for idl compile.
  270. */
  271. public String getIdlopts() {
  272. return idlopts;
  273. }
  274. /**
  275. * Gets file list to compile.
  276. */
  277. public Vector getFileList() {
  278. return compileList;
  279. }
  280. /**
  281. * Sets whether or not to include ant's own classpath in this task's
  282. * classpath.
  283. * Optional; default is <code>true</code>.
  284. */
  285. public void setIncludeantruntime(boolean include) {
  286. includeAntRuntime = include;
  287. }
  288. /**
  289. * Gets whether or not the ant classpath is to be included in the
  290. * task's classpath.
  291. */
  292. public boolean getIncludeantruntime() {
  293. return includeAntRuntime;
  294. }
  295. /**
  296. * task's classpath.
  297. * Enables or disables including the default run-time
  298. * libraries from the executing VM; optional,
  299. * defaults to false
  300. */
  301. public void setIncludejavaruntime(boolean include) {
  302. includeJavaRuntime = include;
  303. }
  304. /**
  305. * Gets whether or not the java runtime should be included in this
  306. * task's classpath.
  307. */
  308. public boolean getIncludejavaruntime() {
  309. return includeJavaRuntime;
  310. }
  311. /**
  312. * Sets the extension directories that will be used during the
  313. * compilation; optional.
  314. */
  315. public void setExtdirs(Path extdirs) {
  316. if (this.extdirs == null) {
  317. this.extdirs = extdirs;
  318. } else {
  319. this.extdirs.append(extdirs);
  320. }
  321. }
  322. /**
  323. * Maybe creates a nested extdirs element.
  324. */
  325. public Path createExtdirs() {
  326. if (extdirs == null) {
  327. extdirs = new Path(getProject());
  328. }
  329. return extdirs.createPath();
  330. }
  331. /**
  332. * Gets the extension directories that will be used during the
  333. * compilation.
  334. */
  335. public Path getExtdirs() {
  336. return extdirs;
  337. }
  338. public Vector getCompileList() {
  339. return compileList;
  340. }
  341. /**
  342. * Sets the compiler implementation to use; optional,
  343. * defaults to the value of the <code>build.rmic</code> property,
  344. * or failing that, default compiler for the current VM
  345. * @since Ant 1.5
  346. */
  347. public void setCompiler(String compiler) {
  348. facade.setImplementation(compiler);
  349. }
  350. /**
  351. * get the name of the current compiler
  352. * @since Ant 1.5
  353. */
  354. public String getCompiler() {
  355. facade.setMagicValue(getProject().getProperty("build.rmic"));
  356. return facade.getImplementation();
  357. }
  358. /**
  359. * Adds an implementation specific command line argument.
  360. * @since Ant 1.5
  361. */
  362. public ImplementationSpecificArgument createCompilerArg() {
  363. ImplementationSpecificArgument arg =
  364. new ImplementationSpecificArgument();
  365. facade.addImplementationArgument(arg);
  366. return arg;
  367. }
  368. /**
  369. * Get the additional implementation specific command line arguments.
  370. * @return array of command line arguments, guaranteed to be non-null.
  371. * @since Ant 1.5
  372. */
  373. public String[] getCurrentCompilerArgs() {
  374. getCompiler();
  375. return facade.getArgs();
  376. }
  377. /**
  378. * execute by creating an instance of an implementation
  379. * class and getting to do the work
  380. */
  381. public void execute() throws BuildException {
  382. if (baseDir == null) {
  383. throw new BuildException("base attribute must be set!", getLocation());
  384. }
  385. if (!baseDir.exists()) {
  386. throw new BuildException("base does not exist!", getLocation());
  387. }
  388. if (verify) {
  389. log("Verify has been turned on.", Project.MSG_VERBOSE);
  390. }
  391. RmicAdapter adapter = RmicAdapterFactory.getRmic(getCompiler(), this);
  392. // now we need to populate the compiler adapter
  393. adapter.setRmic(this);
  394. Path classpath = adapter.getClasspath();
  395. loader = getProject().createClassLoader(classpath);
  396. try {
  397. // scan base dirs to build up compile lists only if a
  398. // specific classname is not given
  399. if (classname == null) {
  400. DirectoryScanner ds = this.getDirectoryScanner(baseDir);
  401. String[] files = ds.getIncludedFiles();
  402. scanDir(baseDir, files, adapter.getMapper());
  403. } else {
  404. // otherwise perform a timestamp comparison - at least
  405. scanDir(baseDir,
  406. new String[] {classname.replace('.',
  407. File.separatorChar)
  408. + ".class"},
  409. adapter.getMapper());
  410. }
  411. int fileCount = compileList.size();
  412. if (fileCount > 0) {
  413. log("RMI Compiling " + fileCount
  414. + " class" + (fileCount > 1 ? "es" : "") + " to " + baseDir,
  415. Project.MSG_INFO);
  416. // finally, lets execute the compiler!!
  417. if (!adapter.execute()) {
  418. throw new BuildException(FAIL_MSG, getLocation());
  419. }
  420. }
  421. /*
  422. * Move the generated source file to the base directory. If
  423. * base directory and sourcebase are the same, the generated
  424. * sources are already in place.
  425. */
  426. if (null != sourceBase && !baseDir.equals(sourceBase)
  427. && fileCount > 0) {
  428. if (idl) {
  429. log("Cannot determine sourcefiles in idl mode, ",
  430. Project.MSG_WARN);
  431. log("sourcebase attribute will be ignored.",
  432. Project.MSG_WARN);
  433. } else {
  434. for (int j = 0; j < fileCount; j++) {
  435. moveGeneratedFile(baseDir, sourceBase,
  436. (String) compileList.elementAt(j),
  437. adapter);
  438. }
  439. }
  440. }
  441. } finally {
  442. compileList.removeAllElements();
  443. }
  444. }
  445. /**
  446. * Move the generated source file(s) to the base directory
  447. *
  448. * @throws org.apache.tools.ant.BuildException When error
  449. * copying/removing files.
  450. */
  451. private void moveGeneratedFile (File baseDir, File sourceBaseFile,
  452. String classname,
  453. RmicAdapter adapter)
  454. throws BuildException {
  455. String classFileName =
  456. classname.replace('.', File.separatorChar) + ".class";
  457. String[] generatedFiles =
  458. adapter.getMapper().mapFileName(classFileName);
  459. for (int i = 0; i < generatedFiles.length; i++) {
  460. final String generatedFile = generatedFiles[i];
  461. if (!generatedFile.endsWith(".class")) {
  462. // don't know how to handle that - a IDL file doesn't
  463. // have a corresponding Java source for example.
  464. continue;
  465. }
  466. final int pos = generatedFile.length() - ".class".length();
  467. String sourceFileName =
  468. generatedFile.substring(0, pos) + ".java";
  469. File oldFile = new File(baseDir, sourceFileName);
  470. if (!oldFile.exists()) {
  471. // no source file generated, nothing to move
  472. continue;
  473. }
  474. File newFile = new File(sourceBaseFile, sourceFileName);
  475. try {
  476. if (filtering) {
  477. fileUtils.copyFile(oldFile, newFile,
  478. new FilterSetCollection(getProject()
  479. .getGlobalFilterSet()));
  480. } else {
  481. fileUtils.copyFile(oldFile, newFile);
  482. }
  483. oldFile.delete();
  484. } catch (IOException ioe) {
  485. String msg = "Failed to copy " + oldFile + " to "
  486. + newFile + " due to " + ioe.getMessage();
  487. throw new BuildException(msg, ioe, getLocation());
  488. }
  489. }
  490. }
  491. /**
  492. * Scans the directory looking for class files to be compiled.
  493. * The result is returned in the class variable compileList.
  494. */
  495. protected void scanDir(File baseDir, String[] files,
  496. FileNameMapper mapper) {
  497. String[] newFiles = files;
  498. if (idl) {
  499. log("will leave uptodate test to rmic implementation in idl mode.",
  500. Project.MSG_VERBOSE);
  501. } else if (iiop
  502. && iiopopts != null && iiopopts.indexOf("-always") > -1) {
  503. log("no uptodate test as -always option has been specified",
  504. Project.MSG_VERBOSE);
  505. } else {
  506. SourceFileScanner sfs = new SourceFileScanner(this);
  507. newFiles = sfs.restrict(files, baseDir, baseDir, mapper);
  508. }
  509. for (int i = 0; i < newFiles.length; i++) {
  510. String classname = newFiles[i].replace(File.separatorChar, '.');
  511. classname = classname.substring(0, classname.lastIndexOf(".class"));
  512. compileList.addElement(classname);
  513. }
  514. }
  515. /**
  516. * Load named class and test whether it can be rmic'ed
  517. */
  518. public boolean isValidRmiRemote(String classname) {
  519. try {
  520. Class testClass = loader.loadClass(classname);
  521. // One cannot RMIC an interface for "classic" RMI (JRMP)
  522. if (testClass.isInterface() && !iiop && !idl) {
  523. return false;
  524. }
  525. return isValidRmiRemote(testClass);
  526. } catch (ClassNotFoundException e) {
  527. log("Unable to verify class " + classname
  528. + ". It could not be found.", Project.MSG_WARN);
  529. } catch (NoClassDefFoundError e) {
  530. log("Unable to verify class " + classname
  531. + ". It is not defined.", Project.MSG_WARN);
  532. } catch (Throwable t) {
  533. log("Unable to verify class " + classname
  534. + ". Loading caused Exception: "
  535. + t.getMessage(), Project.MSG_WARN);
  536. }
  537. // we only get here if an exception has been thrown
  538. return false;
  539. }
  540. /**
  541. * Returns the topmost interface that extends Remote for a given
  542. * class - if one exists.
  543. */
  544. public Class getRemoteInterface(Class testClass) {
  545. if (Remote.class.isAssignableFrom(testClass)) {
  546. Class [] interfaces = testClass.getInterfaces();
  547. if (interfaces != null) {
  548. for (int i = 0; i < interfaces.length; i++) {
  549. if (Remote.class.isAssignableFrom(interfaces[i])) {
  550. return interfaces[i];
  551. }
  552. }
  553. }
  554. }
  555. return null;
  556. }
  557. /**
  558. * Check to see if the class or (super)interfaces implement
  559. * java.rmi.Remote.
  560. */
  561. private boolean isValidRmiRemote (Class testClass) {
  562. return getRemoteInterface(testClass) != null;
  563. }
  564. /**
  565. * Classloader for the user-specified classpath.
  566. */
  567. public ClassLoader getLoader() {
  568. return loader;
  569. }
  570. /**
  571. * Adds an "compiler" attribute to Commandline$Attribute used to
  572. * filter command line attributes based on the current
  573. * implementation.
  574. */
  575. public class ImplementationSpecificArgument extends
  576. org.apache.tools.ant.util.facade.ImplementationSpecificArgument {
  577. /**
  578. * Only pass the specified argument if the
  579. * chosen compiler implementation matches the
  580. * value of this attribute. Legal values are
  581. * the same as those in the above list of
  582. * valid compilers.)
  583. */
  584. public void setCompiler(String impl) {
  585. super.setImplementation(impl);
  586. }
  587. }
  588. }