You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

Property.java 23 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707
  1. /*
  2. * Licensed to the Apache Software Foundation (ASF) under one or more
  3. * contributor license agreements. See the NOTICE file distributed with
  4. * this work for additional information regarding copyright ownership.
  5. * The ASF licenses this file to You under the Apache License, Version 2.0
  6. * (the "License"); you may not use this file except in compliance with
  7. * the License. You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. *
  17. */
  18. package org.apache.tools.ant.taskdefs;
  19. import java.io.File;
  20. import java.io.FileInputStream;
  21. import java.io.IOException;
  22. import java.io.InputStream;
  23. import java.lang.reflect.Method;
  24. import java.net.URL;
  25. import java.util.Enumeration;
  26. import java.util.HashMap;
  27. import java.util.Iterator;
  28. import java.util.Map;
  29. import java.util.Properties;
  30. import java.util.Stack;
  31. import java.util.Vector;
  32. import org.apache.tools.ant.BuildException;
  33. import org.apache.tools.ant.Project;
  34. import org.apache.tools.ant.PropertyHelper;
  35. import org.apache.tools.ant.Task;
  36. import org.apache.tools.ant.types.Path;
  37. import org.apache.tools.ant.types.Reference;
  38. import org.apache.tools.ant.util.FileUtils;
  39. /**
  40. * Sets a property by name, or set of properties (from file or
  41. * resource) in the project. </p>
  42. * Properties are immutable: whoever sets a property first freezes it for the
  43. * rest of the build; they are most definitely not variable.
  44. * <p>There are five ways to set properties:</p>
  45. * <ul>
  46. * <li>By supplying both the <i>name</i> and <i>value</i> attribute.</li>
  47. * <li>By supplying both the <i>name</i> and <i>refid</i> attribute.</li>
  48. * <li>By setting the <i>file</i> attribute with the filename of the property
  49. * file to load. This property file has the format as defined by the file used
  50. * in the class java.util.Properties.</li>
  51. * <li>By setting the <i>resource</i> attribute with the resource name of the
  52. * property file to load. This property file has the format as defined by the
  53. * file used in the class java.util.Properties.</li>
  54. * <li>By setting the <i>environment</i> attribute with a prefix to use.
  55. * Properties will be defined for every environment variable by
  56. * prefixing the supplied name and a period to the name of the variable.</li>
  57. * </ul>
  58. * <p>Although combinations of these ways are possible, only one should be used
  59. * at a time. Problems might occur with the order in which properties are set, for
  60. * instance.</p>
  61. * <p>The value part of the properties being set, might contain references to other
  62. * properties. These references are resolved at the time these properties are set.
  63. * This also holds for properties loaded from a property file.</p>
  64. * Properties are case sensitive.
  65. *
  66. * @since Ant 1.1
  67. *
  68. * @ant.attribute.group name="name" description="One of these, when using the name attribute"
  69. * @ant.attribute.group name="noname" description="One of these, when not using the name attribute"
  70. * @ant.task category="property"
  71. */
  72. public class Property extends Task {
  73. private static class PropertyResolver implements PropertyHelper.PropertyEvaluator {
  74. private ThreadLocal getStack = new ThreadLocal() {
  75. protected Object initialValue() {
  76. return new Stack();
  77. }
  78. };
  79. private ThreadLocal replaceStack = new ThreadLocal() {
  80. protected Object initialValue() {
  81. return new Stack();
  82. }
  83. };
  84. private Map map;
  85. /**
  86. * Construct a new Property.PropertyResolver instance.
  87. */
  88. public PropertyResolver(Map map) {
  89. this.map = map;
  90. }
  91. /* (non-Javadoc)
  92. * @see org.apache.tools.ant.PropertyHelper.PropertyEvaluator#evaluate(java.lang.String, org.apache.tools.ant.PropertyHelper)
  93. */
  94. public Object evaluate(String property, PropertyHelper propertyHelper) {
  95. //our feeble properties don't matter if the PropertyHelper can resolve the property without us:
  96. Stack stk = (Stack) getStack.get();
  97. if (stk.contains(property)) {
  98. return null;
  99. }
  100. stk.push(property);
  101. try {
  102. if (propertyHelper.getProperty(property) != null) {
  103. return null;
  104. }
  105. } finally {
  106. stk.pop();
  107. }
  108. Object value = map.get(property);
  109. if (!(value instanceof String)) {
  110. return null;
  111. }
  112. stk = (Stack) replaceStack.get();
  113. if (stk.contains(property)) {
  114. throw new BuildException("Property " + property + " was circularly defined.");
  115. }
  116. stk.push(property);
  117. try {
  118. return propertyHelper.replaceProperties((String) value);
  119. } finally {
  120. stk.pop();
  121. }
  122. }
  123. }
  124. // CheckStyle:VisibilityModifier OFF - bc
  125. protected String name;
  126. protected String value;
  127. protected File file;
  128. protected URL url;
  129. protected String resource;
  130. protected Path classpath;
  131. protected String env;
  132. protected Reference ref;
  133. protected String prefix;
  134. private Project fallback;
  135. private Object untypedValue;
  136. protected boolean userProperty; // set read-only properties
  137. // CheckStyle:VisibilityModifier ON
  138. /**
  139. * Constructor for Property.
  140. */
  141. public Property() {
  142. this(false);
  143. }
  144. /**
  145. * Constructor for Property.
  146. * @param userProperty if true this is a user property
  147. * @since Ant 1.5
  148. */
  149. protected Property(boolean userProperty) {
  150. this(userProperty, null);
  151. }
  152. /**
  153. * Constructor for Property.
  154. * @param userProperty if true this is a user property
  155. * @param fallback a project to use to look for references if the reference is
  156. * not in the current project
  157. * @since Ant 1.5
  158. */
  159. protected Property(boolean userProperty, Project fallback) {
  160. this.userProperty = userProperty;
  161. this.fallback = fallback;
  162. }
  163. /**
  164. * The name of the property to set.
  165. * @param name property name
  166. */
  167. public void setName(String name) {
  168. this.name = name;
  169. }
  170. /**
  171. * Get the property name.
  172. * @return the property name
  173. */
  174. public String getName() {
  175. return name;
  176. }
  177. /**
  178. * Sets the property to the absolute filename of the
  179. * given file. If the value of this attribute is an absolute path, it
  180. * is left unchanged (with / and \ characters converted to the
  181. * current platforms conventions). Otherwise it is taken as a path
  182. * relative to the project's basedir and expanded.
  183. * @param location path to set
  184. *
  185. * @ant.attribute group="name"
  186. */
  187. public void setLocation(File location) {
  188. setValue(location.getAbsolutePath());
  189. }
  190. /* the following method is first in source so IH will pick it up first:
  191. * Hopefully we'll never get any classes compiled by wise-guy compilers that behave otherwise...
  192. */
  193. /**
  194. * Set the value of the property.
  195. * @param value
  196. */
  197. public void setValue(Object value) {
  198. this.untypedValue = value;
  199. //preserve protected string value for subclasses :(
  200. this.value = value == null ? null : value.toString();
  201. }
  202. /**
  203. * Set the value of the property as a String.
  204. * @param value value to assign
  205. *
  206. * @ant.attribute group="name"
  207. */
  208. public void setValue(String value) {
  209. setValue((Object) value);
  210. }
  211. /**
  212. * Get the property value.
  213. * @return the property value
  214. */
  215. public String getValue() {
  216. return value;
  217. }
  218. /**
  219. * Filename of a property file to load.
  220. * @param file filename
  221. *
  222. * @ant.attribute group="noname"
  223. */
  224. public void setFile(File file) {
  225. this.file = file;
  226. }
  227. /**
  228. * Get the file attribute.
  229. * @return the file attribute
  230. */
  231. public File getFile() {
  232. return file;
  233. }
  234. /**
  235. * The url from which to load properties.
  236. * @param url url string
  237. *
  238. * @ant.attribute group="noname"
  239. */
  240. public void setUrl(URL url) {
  241. this.url = url;
  242. }
  243. /**
  244. * Get the url attribute.
  245. * @return the url attribute
  246. */
  247. public URL getUrl() {
  248. return url;
  249. }
  250. /**
  251. * Prefix to apply to properties loaded using <code>file</code>
  252. * or <code>resource</code>.
  253. * A "." is appended to the prefix if not specified.
  254. * @param prefix prefix string
  255. * @since Ant 1.5
  256. */
  257. public void setPrefix(String prefix) {
  258. this.prefix = prefix;
  259. if (!prefix.endsWith(".")) {
  260. this.prefix += ".";
  261. }
  262. }
  263. /**
  264. * Get the prefix attribute.
  265. * @return the prefix attribute
  266. * @since Ant 1.5
  267. */
  268. public String getPrefix() {
  269. return prefix;
  270. }
  271. /**
  272. * Sets a reference to an Ant datatype
  273. * declared elsewhere.
  274. * Only yields reasonable results for references
  275. * PATH like structures or properties.
  276. * @param ref reference
  277. *
  278. * @ant.attribute group="name"
  279. */
  280. public void setRefid(Reference ref) {
  281. this.ref = ref;
  282. }
  283. /**
  284. * Get the refid attribute.
  285. * @return the refid attribute
  286. */
  287. public Reference getRefid() {
  288. return ref;
  289. }
  290. /**
  291. * The resource name of a property file to load
  292. * @param resource resource on classpath
  293. *
  294. * @ant.attribute group="noname"
  295. */
  296. public void setResource(String resource) {
  297. this.resource = resource;
  298. }
  299. /**
  300. * Get the resource attribute.
  301. * @return the resource attribute
  302. */
  303. public String getResource() {
  304. return resource;
  305. }
  306. /**
  307. * Prefix to use when retrieving environment variables.
  308. * Thus if you specify environment=&quot;myenv&quot;
  309. * you will be able to access OS-specific
  310. * environment variables via property names &quot;myenv.PATH&quot; or
  311. * &quot;myenv.TERM&quot;.
  312. * <p>
  313. * Note that if you supply a property name with a final
  314. * &quot;.&quot; it will not be doubled. ie environment=&quot;myenv.&quot; will still
  315. * allow access of environment variables through &quot;myenv.PATH&quot; and
  316. * &quot;myenv.TERM&quot;. This functionality is currently only implemented
  317. * on select platforms. Feel free to send patches to increase the number of platforms
  318. * this functionality is supported on ;).<br>
  319. * Note also that properties are case sensitive, even if the
  320. * environment variables on your operating system are not, e.g. it
  321. * will be ${env.Path} not ${env.PATH} on Windows 2000.
  322. * @param env prefix
  323. *
  324. * @ant.attribute group="noname"
  325. */
  326. public void setEnvironment(String env) {
  327. this.env = env;
  328. }
  329. /**
  330. * Get the environment attribute.
  331. * @return the environment attribute
  332. * @since Ant 1.5
  333. */
  334. public String getEnvironment() {
  335. return env;
  336. }
  337. /**
  338. * The classpath to use when looking up a resource.
  339. * @param classpath to add to any existing classpath
  340. */
  341. public void setClasspath(Path classpath) {
  342. if (this.classpath == null) {
  343. this.classpath = classpath;
  344. } else {
  345. this.classpath.append(classpath);
  346. }
  347. }
  348. /**
  349. * The classpath to use when looking up a resource.
  350. * @return a path to be configured
  351. */
  352. public Path createClasspath() {
  353. if (this.classpath == null) {
  354. this.classpath = new Path(getProject());
  355. }
  356. return this.classpath.createPath();
  357. }
  358. /**
  359. * the classpath to use when looking up a resource,
  360. * given as reference to a &lt;path&gt; defined elsewhere
  361. * @param r a reference to a classpath
  362. */
  363. public void setClasspathRef(Reference r) {
  364. createClasspath().setRefid(r);
  365. }
  366. /**
  367. * Get the classpath used when looking up a resource.
  368. * @return the classpath
  369. * @since Ant 1.5
  370. */
  371. public Path getClasspath() {
  372. return classpath;
  373. }
  374. /**
  375. * @param userProperty ignored
  376. * @deprecated since 1.5.x.
  377. * This was never a supported feature and has been
  378. * deprecated without replacement.
  379. * @ant.attribute ignore="true"
  380. */
  381. public void setUserProperty(boolean userProperty) {
  382. log("DEPRECATED: Ignoring request to set user property in Property"
  383. + " task.", Project.MSG_WARN);
  384. }
  385. /**
  386. * get the value of this property
  387. * @return the current value or the empty string
  388. */
  389. public String toString() {
  390. return value == null ? "" : value;
  391. }
  392. /**
  393. * set the property in the project to the value.
  394. * if the task was give a file, resource or env attribute
  395. * here is where it is loaded
  396. * @throws BuildException on error
  397. */
  398. public void execute() throws BuildException {
  399. if (getProject() == null) {
  400. throw new IllegalStateException("project has not been set");
  401. }
  402. if (name != null) {
  403. if (untypedValue == null && ref == null) {
  404. throw new BuildException("You must specify value, location or "
  405. + "refid with the name attribute",
  406. getLocation());
  407. }
  408. } else {
  409. if (url == null && file == null && resource == null && env == null) {
  410. throw new BuildException("You must specify url, file, resource or "
  411. + "environment when not using the "
  412. + "name attribute", getLocation());
  413. }
  414. }
  415. if (url == null && file == null && resource == null && prefix != null) {
  416. throw new BuildException("Prefix is only valid when loading from "
  417. + "a url, file or resource", getLocation());
  418. }
  419. if (name != null && untypedValue != null) {
  420. addProperty(name, untypedValue);
  421. }
  422. if (file != null) {
  423. loadFile(file);
  424. }
  425. if (url != null) {
  426. loadUrl(url);
  427. }
  428. if (resource != null) {
  429. loadResource(resource);
  430. }
  431. if (env != null) {
  432. loadEnvironment(env);
  433. }
  434. if ((name != null) && (ref != null)) {
  435. try {
  436. addProperty(name,
  437. ref.getReferencedObject(getProject()).toString());
  438. } catch (BuildException be) {
  439. if (fallback != null) {
  440. addProperty(name,
  441. ref.getReferencedObject(fallback).toString());
  442. } else {
  443. throw be;
  444. }
  445. }
  446. }
  447. }
  448. /**
  449. * load properties from a url
  450. * @param url url to load from
  451. * @throws BuildException on error
  452. */
  453. protected void loadUrl(URL url) throws BuildException {
  454. Properties props = new Properties();
  455. log("Loading " + url, Project.MSG_VERBOSE);
  456. try {
  457. InputStream is = url.openStream();
  458. try {
  459. loadProperties(props, is, url.getFile().endsWith(".xml"));
  460. } finally {
  461. if (is != null) {
  462. is.close();
  463. }
  464. }
  465. addProperties(props);
  466. } catch (IOException ex) {
  467. throw new BuildException(ex, getLocation());
  468. }
  469. }
  470. /**
  471. * Loads the properties defined in the InputStream into the given
  472. * property. On Java5+ it supports reading from XML based property
  473. * definition.
  474. * @param props The property object to load into
  475. * @param is The input stream from where to load
  476. * @param isXml <tt>true</tt> if we should try to load from xml
  477. * @throws IOException if something goes wrong
  478. * @since 1.7.1
  479. * @see http://java.sun.com/dtd/properties.dtd
  480. * @see java.util.Properties#loadFromXML(InputStream)
  481. */
  482. private void loadProperties(Properties props, InputStream is, boolean isXml) throws IOException {
  483. if (isXml) {
  484. // load the xml based property definition
  485. // use reflection because of bwc to Java 1.3
  486. try {
  487. Method loadXmlMethod = props.getClass().getMethod("loadFromXML",
  488. new Class[] { InputStream.class });
  489. loadXmlMethod.invoke(props, new Object[] { is });
  490. } catch (NoSuchMethodException e) {
  491. e.printStackTrace();
  492. log("Can not load xml based property definition on Java < 5");
  493. } catch (Exception e) {
  494. // no-op
  495. e.printStackTrace();
  496. }
  497. } else {
  498. // load ".properties" format
  499. props.load(is);
  500. }
  501. }
  502. /**
  503. * load properties from a file
  504. * @param file file to load
  505. * @throws BuildException on error
  506. */
  507. protected void loadFile(File file) throws BuildException {
  508. Properties props = new Properties();
  509. log("Loading " + file.getAbsolutePath(), Project.MSG_VERBOSE);
  510. try {
  511. if (file.exists()) {
  512. FileInputStream fis = null;
  513. try {
  514. fis = new FileInputStream(file);
  515. loadProperties(props, fis, file.getName().endsWith(".xml"));
  516. } finally {
  517. FileUtils.close(fis);
  518. }
  519. addProperties(props);
  520. } else {
  521. log("Unable to find property file: " + file.getAbsolutePath(),
  522. Project.MSG_VERBOSE);
  523. }
  524. } catch (IOException ex) {
  525. throw new BuildException(ex, getLocation());
  526. }
  527. }
  528. /**
  529. * load properties from a resource in the current classpath
  530. * @param name name of resource to load
  531. */
  532. protected void loadResource(String name) {
  533. Properties props = new Properties();
  534. log("Resource Loading " + name, Project.MSG_VERBOSE);
  535. InputStream is = null;
  536. try {
  537. ClassLoader cL = null;
  538. if (classpath != null) {
  539. cL = getProject().createClassLoader(classpath);
  540. } else {
  541. cL = this.getClass().getClassLoader();
  542. }
  543. if (cL == null) {
  544. is = ClassLoader.getSystemResourceAsStream(name);
  545. } else {
  546. is = cL.getResourceAsStream(name);
  547. }
  548. if (is != null) {
  549. loadProperties(props, is, name.endsWith(".xml"));
  550. addProperties(props);
  551. } else {
  552. log("Unable to find resource " + name, Project.MSG_WARN);
  553. }
  554. } catch (IOException ex) {
  555. throw new BuildException(ex, getLocation());
  556. } finally {
  557. if (is != null) {
  558. try {
  559. is.close();
  560. } catch (IOException e) {
  561. // ignore
  562. }
  563. }
  564. }
  565. }
  566. /**
  567. * load the environment values
  568. * @param prefix prefix to place before them
  569. */
  570. protected void loadEnvironment(String prefix) {
  571. Properties props = new Properties();
  572. if (!prefix.endsWith(".")) {
  573. prefix += ".";
  574. }
  575. log("Loading Environment " + prefix, Project.MSG_VERBOSE);
  576. Vector osEnv = Execute.getProcEnvironment();
  577. for (Enumeration e = osEnv.elements(); e.hasMoreElements();) {
  578. String entry = (String) e.nextElement();
  579. int pos = entry.indexOf('=');
  580. if (pos == -1) {
  581. log("Ignoring: " + entry, Project.MSG_WARN);
  582. } else {
  583. props.put(prefix + entry.substring(0, pos),
  584. entry.substring(pos + 1));
  585. }
  586. }
  587. addProperties(props);
  588. }
  589. /**
  590. * iterate through a set of properties,
  591. * resolve them then assign them
  592. * @param props the properties to iterate over
  593. */
  594. protected void addProperties(Properties props) {
  595. HashMap m = new HashMap(props);
  596. resolveAllProperties(m);
  597. for (Iterator it = m.keySet().iterator(); it.hasNext();) {
  598. Object k = it.next();
  599. if (k instanceof String) {
  600. String propertyName = (String) k;
  601. if (prefix != null) {
  602. propertyName = prefix + propertyName;
  603. }
  604. addProperty(propertyName, m.get(k));
  605. }
  606. }
  607. }
  608. /**
  609. * add a name value pair to the project property set
  610. * @param n name of property
  611. * @param v value to set
  612. */
  613. protected void addProperty(String n, String v) {
  614. addProperty(n, (Object) v);
  615. }
  616. /**
  617. * add a name value pair to the project property set
  618. * @param n name of property
  619. * @param v value to set
  620. * @since Ant 1.8
  621. */
  622. protected void addProperty(String n, Object v) {
  623. PropertyHelper ph = PropertyHelper.getPropertyHelper(getProject());
  624. if (userProperty) {
  625. if (ph.getUserProperty(n) == null) {
  626. ph.setInheritedProperty(n, v);
  627. } else {
  628. log("Override ignored for " + n, Project.MSG_VERBOSE);
  629. }
  630. } else {
  631. ph.setNewProperty(n, v);
  632. }
  633. }
  634. /**
  635. * resolve properties inside a properties hashtable
  636. * @param props properties object to resolve
  637. */
  638. private void resolveAllProperties(Map props) throws BuildException {
  639. PropertyHelper propertyHelper = (PropertyHelper) PropertyHelper.getPropertyHelper(
  640. getProject()).clone();
  641. propertyHelper.add(new PropertyResolver(props));
  642. for (Iterator it = props.keySet().iterator(); it.hasNext();) {
  643. Object k = it.next();
  644. if (k instanceof String) {
  645. Object value = propertyHelper.getProperty((String) k);
  646. props.put(k, value);
  647. }
  648. }
  649. }
  650. }