1. /*
  2. * Copyright 2001-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.io.InputStream;
  21. import java.net.URL;
  22. import java.util.Map;
  23. import java.util.HashMap;
  24. import java.util.Enumeration;
  25. import java.util.Locale;
  26. import java.util.NoSuchElementException;
  27. import java.util.Properties;
  28. import org.apache.tools.ant.AntTypeDefinition;
  29. import org.apache.tools.ant.ComponentHelper;
  30. import org.apache.tools.ant.BuildException;
  31. import org.apache.tools.ant.Project;
  32. import org.apache.tools.ant.ProjectHelper;
  33. import org.apache.tools.ant.types.EnumeratedAttribute;
  34. /**
  35. * Base class for Taskdef and Typedef - handles all
  36. * the attributes for Typedef. The uri and class
  37. * handling is handled by DefBase
  38. *
  39. * @since Ant 1.4
  40. */
  41. public abstract class Definer extends DefBase {
  42. private static class ResourceStack extends ThreadLocal {
  43. public Object initialValue() {
  44. return new HashMap();
  45. }
  46. Map getStack() {
  47. return (Map) get();
  48. }
  49. }
  50. private static ResourceStack resourceStack = new ResourceStack();
  51. private String name;
  52. private String classname;
  53. private File file;
  54. private String resource;
  55. private int format = Format.PROPERTIES;
  56. private boolean definerSet = false;
  57. private int onError = OnError.FAIL;
  58. private String adapter;
  59. private String adaptTo;
  60. private Class adapterClass;
  61. private Class adaptToClass;
  62. /**
  63. * Enumerated type for onError attribute
  64. *
  65. * @see EnumeratedAttribute
  66. */
  67. public static class OnError extends EnumeratedAttribute {
  68. /** Enumerated values */
  69. public static final int FAIL = 0, REPORT = 1, IGNORE = 2;
  70. /**
  71. * Constructor
  72. */
  73. public OnError() {
  74. super();
  75. }
  76. /**
  77. * Constructor using a string.
  78. * @param value the value of the attribute
  79. */
  80. public OnError(String value) {
  81. setValue(value);
  82. }
  83. /**
  84. * get the values
  85. * @return an array of the allowed values for this attribute.
  86. */
  87. public String[] getValues() {
  88. return new String[] {"fail", "report", "ignore"};
  89. }
  90. }
  91. /**
  92. * Enumerated type for format attribute
  93. *
  94. * @see EnumeratedAttribute
  95. */
  96. public static class Format extends EnumeratedAttribute {
  97. /** Enumerated values */
  98. public static final int PROPERTIES = 0, XML = 1;
  99. /**
  100. * get the values
  101. * @return an array of the allowed values for this attribute.
  102. */
  103. public String[] getValues() {
  104. return new String[] {"properties", "xml"};
  105. }
  106. }
  107. /**
  108. * What to do if there is an error in loading the class.
  109. * <dl>
  110. * <li>error - throw build exception</li>
  111. * <li>report - output at warning level</li>
  112. * <li>ignore - output at debug level</li>
  113. * </dl>
  114. *
  115. * @param onError an <code>OnError</code> value
  116. */
  117. public void setOnError(OnError onError) {
  118. this.onError = onError.getIndex();
  119. }
  120. /**
  121. * Sets the format of the file or resource
  122. * @param format the enumerated value - xml or properties
  123. */
  124. public void setFormat(Format format) {
  125. this.format = format.getIndex();
  126. }
  127. /**
  128. * @return the name for this definition
  129. */
  130. public String getName() {
  131. return name;
  132. }
  133. /**
  134. * @return the file containing definitions
  135. */
  136. public File getFile() {
  137. return file;
  138. }
  139. /**
  140. * @return the resource containing definitions
  141. */
  142. public String getResource() {
  143. return resource;
  144. }
  145. /**
  146. * Run the definition.
  147. *
  148. * @exception BuildException if an error occurs
  149. */
  150. public void execute() throws BuildException {
  151. ClassLoader al = createLoader();
  152. if (!definerSet) {
  153. throw new BuildException(
  154. "name, file or resource attribute of "
  155. + getTaskName() + " is undefined", getLocation());
  156. }
  157. if (name != null) {
  158. if (classname == null) {
  159. throw new BuildException(
  160. "classname attribute of " + getTaskName() + " element "
  161. + "is undefined", getLocation());
  162. }
  163. addDefinition(al, name, classname);
  164. } else {
  165. if (classname != null) {
  166. String msg = "You must not specify classname "
  167. + "together with file or resource.";
  168. throw new BuildException(msg, getLocation());
  169. }
  170. Enumeration/*<URL>*/ urls = null;
  171. if (file != null) {
  172. final URL url = fileToURL();
  173. if (url == null) {
  174. return;
  175. }
  176. urls = new Enumeration() {
  177. private boolean more = true;
  178. public boolean hasMoreElements() {
  179. return more;
  180. }
  181. public Object nextElement() throws NoSuchElementException {
  182. if (more) {
  183. more = false;
  184. return url;
  185. } else {
  186. throw new NoSuchElementException();
  187. }
  188. }
  189. };
  190. } else {
  191. urls = resourceToURLs(al);
  192. }
  193. while (urls.hasMoreElements()) {
  194. URL url = (URL) urls.nextElement();
  195. int format = this.format;
  196. if (url.toString().toLowerCase(Locale.US).endsWith(".xml")) {
  197. format = Format.XML;
  198. }
  199. if (format == Format.PROPERTIES) {
  200. loadProperties(al, url);
  201. break;
  202. } else {
  203. if (resourceStack.getStack().get(url) != null) {
  204. log("Warning: Recursive loading of " + url
  205. + " ignored"
  206. + " at " + getLocation()
  207. + " originally loaded at "
  208. + resourceStack.getStack().get(url),
  209. Project.MSG_WARN);
  210. } else {
  211. try {
  212. resourceStack.getStack().put(url, getLocation());
  213. loadAntlib(al, url);
  214. } finally {
  215. resourceStack.getStack().remove(url);
  216. }
  217. }
  218. }
  219. }
  220. }
  221. }
  222. private URL fileToURL() {
  223. if (!(file.exists())) {
  224. log("File " + file + " does not exist", Project.MSG_WARN);
  225. return null;
  226. }
  227. if (!(file.isFile())) {
  228. log("File " + file + " is not a file", Project.MSG_WARN);
  229. return null;
  230. }
  231. try {
  232. return file.toURL();
  233. } catch (Exception ex) {
  234. log("File " + file + " cannot use as URL: "
  235. + ex.toString(), Project.MSG_WARN);
  236. return null;
  237. }
  238. }
  239. private Enumeration/*<URL>*/ resourceToURLs(ClassLoader classLoader) {
  240. Enumeration ret;
  241. try {
  242. ret = classLoader.getResources(resource);
  243. } catch (IOException e) {
  244. throw new BuildException(
  245. "Could not fetch resources named " + resource,
  246. e, getLocation());
  247. }
  248. if (!ret.hasMoreElements()) {
  249. if (onError != OnError.IGNORE) {
  250. log("Could not load definitions from resource "
  251. + resource + ". It could not be found.",
  252. Project.MSG_WARN);
  253. }
  254. }
  255. return ret;
  256. }
  257. /**
  258. * Load type definitions as properties from a url.
  259. *
  260. * @param al the classloader to use
  261. * @param url the url to get the definitions from
  262. */
  263. protected void loadProperties(ClassLoader al, URL url) {
  264. InputStream is = null;
  265. try {
  266. is = url.openStream();
  267. if (is == null) {
  268. log("Could not load definitions from " + url,
  269. Project.MSG_WARN);
  270. return;
  271. }
  272. Properties props = new Properties();
  273. props.load(is);
  274. Enumeration keys = props.keys();
  275. while (keys.hasMoreElements()) {
  276. name = ((String) keys.nextElement());
  277. classname = props.getProperty(name);
  278. addDefinition(al, name, classname);
  279. }
  280. } catch (IOException ex) {
  281. throw new BuildException(ex, getLocation());
  282. } finally {
  283. if (is != null) {
  284. try {
  285. is.close();
  286. } catch (IOException e) {
  287. // ignore
  288. }
  289. }
  290. }
  291. }
  292. /**
  293. * Load an antlib from a url.
  294. *
  295. * @param classLoader the classloader to use.
  296. * @param url the url to load the definitions from.
  297. */
  298. private void loadAntlib(ClassLoader classLoader, URL url) {
  299. try {
  300. Antlib antlib = Antlib.createAntlib(getProject(), url, getURI());
  301. antlib.setClassLoader(classLoader);
  302. antlib.setURI(getURI());
  303. antlib.perform();
  304. } catch (BuildException ex) {
  305. throw ProjectHelper.addLocationToBuildException(
  306. ex, getLocation());
  307. }
  308. }
  309. /**
  310. * Name of the property file to load
  311. * ant name/classname pairs from.
  312. * @param file the file
  313. */
  314. public void setFile(File file) {
  315. if (definerSet) {
  316. tooManyDefinitions();
  317. }
  318. definerSet = true;
  319. this.file = file;
  320. }
  321. /**
  322. * Name of the property resource to load
  323. * ant name/classname pairs from.
  324. * @param res the resource to use
  325. */
  326. public void setResource(String res) {
  327. if (definerSet) {
  328. tooManyDefinitions();
  329. }
  330. definerSet = true;
  331. this.resource = res;
  332. }
  333. /**
  334. * Name of the definition
  335. * @param name the name of the definition
  336. */
  337. public void setName(String name) {
  338. if (definerSet) {
  339. tooManyDefinitions();
  340. }
  341. definerSet = true;
  342. this.name = name;
  343. }
  344. /**
  345. * Returns the classname of the object we are defining.
  346. * May be <code>null</code>.
  347. * @return the class name
  348. */
  349. public String getClassname() {
  350. return classname;
  351. }
  352. /**
  353. * The full class name of the object being defined.
  354. * Required, unless file or resource have
  355. * been specified.
  356. * @param classname the name of the class
  357. */
  358. public void setClassname(String classname) {
  359. this.classname = classname;
  360. }
  361. /**
  362. * Set the class name of the adapter class.
  363. * An adapter class is used to proxy the
  364. * definition class. It is used if the
  365. * definition class is not assignable to
  366. * the adaptto class, or if the adaptto
  367. * class is not present.
  368. *
  369. * @param adapter the name of the adapter class
  370. */
  371. public void setAdapter(String adapter) {
  372. this.adapter = adapter;
  373. }
  374. /**
  375. * Set the adapter class.
  376. *
  377. * @param adapterClass the class to use to adapt the definition class
  378. */
  379. protected void setAdapterClass(Class adapterClass) {
  380. this.adapterClass = adapterClass;
  381. }
  382. /**
  383. * Set the classname of the class that the definition
  384. * must be compatible with, either directly or
  385. * by use of the adapter class.
  386. *
  387. * @param adaptTo the name of the adaptto class
  388. */
  389. public void setAdaptTo(String adaptTo) {
  390. this.adaptTo = adaptTo;
  391. }
  392. /**
  393. * Set the class for adaptToClass, to be
  394. * used by derived classes, used instead of
  395. * the adaptTo attribute.
  396. *
  397. * @param adaptToClass the class for adapto.
  398. */
  399. protected void setAdaptToClass(Class adaptToClass) {
  400. this.adaptToClass = adaptToClass;
  401. }
  402. /**
  403. * Add a definition using the attributes of Definer
  404. *
  405. * @param al the ClassLoader to use
  406. * @param name the name of the definition
  407. * @param classname the classname of the definition
  408. * @exception BuildException if an error occurs
  409. */
  410. protected void addDefinition(ClassLoader al, String name, String classname)
  411. throws BuildException {
  412. Class cl = null;
  413. try {
  414. try {
  415. name = ProjectHelper.genComponentName(getURI(), name);
  416. if (onError != OnError.IGNORE) {
  417. cl = Class.forName(classname, true, al);
  418. }
  419. if (adapter != null) {
  420. adapterClass = Class.forName(adapter, true, al);
  421. }
  422. if (adaptTo != null) {
  423. adaptToClass = Class.forName(adaptTo, true, al);
  424. }
  425. AntTypeDefinition def = new AntTypeDefinition();
  426. def.setName(name);
  427. def.setClassName(classname);
  428. def.setClass(cl);
  429. def.setAdapterClass(adapterClass);
  430. def.setAdaptToClass(adaptToClass);
  431. def.setClassLoader(al);
  432. if (cl != null) {
  433. def.checkClass(getProject());
  434. }
  435. ComponentHelper.getComponentHelper(getProject())
  436. .addDataTypeDefinition(def);
  437. } catch (ClassNotFoundException cnfe) {
  438. String msg = getTaskName() + " class " + classname
  439. + " cannot be found";
  440. throw new BuildException(msg, cnfe, getLocation());
  441. } catch (NoClassDefFoundError ncdfe) {
  442. String msg = getTaskName() + " A class needed by class "
  443. + classname + " cannot be found: " + ncdfe.getMessage();
  444. throw new BuildException(msg, ncdfe, getLocation());
  445. }
  446. } catch (BuildException ex) {
  447. switch (onError) {
  448. case OnError.FAIL:
  449. throw ex;
  450. case OnError.REPORT:
  451. log(ex.getLocation() + "Warning: " + ex.getMessage(),
  452. Project.MSG_WARN);
  453. break;
  454. default:
  455. log(ex.getLocation() + ex.getMessage(),
  456. Project.MSG_DEBUG);
  457. }
  458. }
  459. }
  460. private void tooManyDefinitions() {
  461. throw new BuildException(
  462. "Only one of the attributes name,file,resource"
  463. + " can be set", getLocation());
  464. }
  465. }