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 24 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737
  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.Vector;
  31. import org.apache.tools.ant.AntClassLoader;
  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. import org.apache.tools.ant.property.ResolvePropertyMap;
  40. /**
  41. * Sets a property by name, or set of properties (from file or
  42. * resource) in the project. </p>
  43. * Properties are immutable: whoever sets a property first freezes it for the
  44. * rest of the build; they are most definitely not variable.
  45. * <p>There are seven ways to set properties:</p>
  46. * <ul>
  47. * <li>By supplying both the <i>name</i> and <i>value</i> attribute.</li>
  48. * <li>By supplying the <i>name</i> and nested text.</li>
  49. * <li>By supplying both the <i>name</i> and <i>refid</i> attribute.</li>
  50. * <li>By setting the <i>file</i> attribute with the filename of the property
  51. * file to load. This property file has the format as defined by the file used
  52. * in the class java.util.Properties.</li>
  53. * <li>By setting the <i>url</i> attribute with the url from which to load the
  54. * properties. This url must be directed to a file that has the format as defined
  55. * by the file used in the class java.util.Properties.</li>
  56. * <li>By setting the <i>resource</i> attribute with the resource name of the
  57. * property file to load. This property file has the format as defined by the
  58. * file used in the class java.util.Properties.</li>
  59. * <li>By setting the <i>environment</i> attribute with a prefix to use.
  60. * Properties will be defined for every environment variable by
  61. * prefixing the supplied name and a period to the name of the variable.</li>
  62. * </ul>
  63. * <p>Although combinations of these ways are possible, only one should be used
  64. * at a time. Problems might occur with the order in which properties are set, for
  65. * instance.</p>
  66. * <p>The value part of the properties being set, might contain references to other
  67. * properties. These references are resolved at the time these properties are set.
  68. * This also holds for properties loaded from a property file.</p>
  69. * Properties are case sensitive.
  70. *
  71. * @since Ant 1.1
  72. *
  73. * @ant.attribute.group name="name" description="One of these, when using the name attribute"
  74. * @ant.attribute.group name="noname" description="One of these, when not using the name attribute"
  75. * @ant.task category="property"
  76. */
  77. public class Property extends Task {
  78. // CheckStyle:VisibilityModifier OFF - bc
  79. protected String name;
  80. protected String value;
  81. protected File file;
  82. protected URL url;
  83. protected String resource;
  84. protected Path classpath;
  85. protected String env;
  86. protected Reference ref;
  87. protected String prefix;
  88. private Project fallback;
  89. private Object untypedValue;
  90. private boolean valueAttributeUsed = false;
  91. private boolean relative = false;
  92. private File basedir;
  93. private boolean prefixValues = false;
  94. protected boolean userProperty; // set read-only properties
  95. // CheckStyle:VisibilityModifier ON
  96. /**
  97. * Constructor for Property.
  98. */
  99. public Property() {
  100. this(false);
  101. }
  102. /**
  103. * Constructor for Property.
  104. * @param userProperty if true this is a user property
  105. * @since Ant 1.5
  106. */
  107. protected Property(boolean userProperty) {
  108. this(userProperty, null);
  109. }
  110. /**
  111. * Constructor for Property.
  112. * @param userProperty if true this is a user property
  113. * @param fallback a project to use to look for references if the reference is
  114. * not in the current project
  115. * @since Ant 1.5
  116. */
  117. protected Property(boolean userProperty, Project fallback) {
  118. this.userProperty = userProperty;
  119. this.fallback = fallback;
  120. }
  121. /**
  122. * Sets 'relative' attribute.
  123. * @param relative new value
  124. * @since Ant 1.8.0
  125. */
  126. public void setRelative(boolean relative) {
  127. this.relative = relative;
  128. }
  129. /**
  130. * Sets 'basedir' attribute.
  131. * @param basedir new value
  132. * @since Ant 1.8.0
  133. */
  134. public void setBasedir(File basedir) {
  135. this.basedir = basedir;
  136. }
  137. /**
  138. * The name of the property to set.
  139. * @param name property name
  140. */
  141. public void setName(String name) {
  142. this.name = name;
  143. }
  144. /**
  145. * Get the property name.
  146. * @return the property name
  147. */
  148. public String getName() {
  149. return name;
  150. }
  151. /**
  152. * Sets the property to the absolute filename of the
  153. * given file. If the value of this attribute is an absolute path, it
  154. * is left unchanged (with / and \ characters converted to the
  155. * current platforms conventions). Otherwise it is taken as a path
  156. * relative to the project's basedir and expanded.
  157. * @param location path to set
  158. *
  159. * @ant.attribute group="name"
  160. */
  161. public void setLocation(File location) {
  162. if (relative) {
  163. internalSetValue(location);
  164. } else {
  165. setValue(location.getAbsolutePath());
  166. }
  167. }
  168. /* the following method is first in source so IH will pick it up first:
  169. * Hopefully we'll never get any classes compiled by wise-guy compilers that behave otherwise...
  170. */
  171. /**
  172. * Set the value of the property.
  173. * @param value the value to use.
  174. */
  175. public void setValue(Object value) {
  176. valueAttributeUsed = true;
  177. internalSetValue(value);
  178. }
  179. private void internalSetValue(Object value) {
  180. this.untypedValue = value;
  181. //preserve protected string value for subclasses :(
  182. this.value = value == null ? null : value.toString();
  183. }
  184. /**
  185. * Set the value of the property as a String.
  186. * @param value value to assign
  187. *
  188. * @ant.attribute group="name"
  189. */
  190. public void setValue(String value) {
  191. setValue((Object) value);
  192. }
  193. /**
  194. * Set a (multiline) property as nested text.
  195. * @param msg the text to append to the output text
  196. * @since Ant 1.8.0
  197. */
  198. public void addText(String msg) {
  199. if (!valueAttributeUsed) {
  200. msg = getProject().replaceProperties(msg);
  201. String currentValue = getValue();
  202. if (currentValue != null) {
  203. msg = currentValue + msg;
  204. }
  205. internalSetValue(msg);
  206. } else if (msg.trim().length() > 0) {
  207. throw new BuildException("can't combine nested text with value"
  208. + " attribute");
  209. }
  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 != null && !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. * Whether to apply the prefix when expanding properties on the
  273. * right hand side of a properties file as well.
  274. *
  275. * @since Ant 1.8.2
  276. */
  277. public void setPrefixValues(boolean b) {
  278. prefixValues = b;
  279. }
  280. /**
  281. * Whether to apply the prefix when expanding properties on the
  282. * right hand side of a properties file as well.
  283. *
  284. * @since Ant 1.8.2
  285. */
  286. public boolean getPrefixValues() {
  287. return prefixValues;
  288. }
  289. /**
  290. * Sets a reference to an Ant datatype
  291. * declared elsewhere.
  292. * Only yields reasonable results for references
  293. * PATH like structures or properties.
  294. * @param ref reference
  295. *
  296. * @ant.attribute group="name"
  297. */
  298. public void setRefid(Reference ref) {
  299. this.ref = ref;
  300. }
  301. /**
  302. * Get the refid attribute.
  303. * @return the refid attribute
  304. */
  305. public Reference getRefid() {
  306. return ref;
  307. }
  308. /**
  309. * The resource name of a property file to load
  310. * @param resource resource on classpath
  311. *
  312. * @ant.attribute group="noname"
  313. */
  314. public void setResource(String resource) {
  315. this.resource = resource;
  316. }
  317. /**
  318. * Get the resource attribute.
  319. * @return the resource attribute
  320. */
  321. public String getResource() {
  322. return resource;
  323. }
  324. /**
  325. * Prefix to use when retrieving environment variables.
  326. * Thus if you specify environment=&quot;myenv&quot;
  327. * you will be able to access OS-specific
  328. * environment variables via property names &quot;myenv.PATH&quot; or
  329. * &quot;myenv.TERM&quot;.
  330. * <p>
  331. * Note that if you supply a property name with a final
  332. * &quot;.&quot; it will not be doubled. ie environment=&quot;myenv.&quot; will still
  333. * allow access of environment variables through &quot;myenv.PATH&quot; and
  334. * &quot;myenv.TERM&quot;. This functionality is currently only implemented
  335. * on select platforms. Feel free to send patches to increase the number of platforms
  336. * this functionality is supported on ;).<br>
  337. * Note also that properties are case sensitive, even if the
  338. * environment variables on your operating system are not, e.g. it
  339. * will be ${env.Path} not ${env.PATH} on Windows 2000.
  340. * @param env prefix
  341. *
  342. * @ant.attribute group="noname"
  343. */
  344. public void setEnvironment(String env) {
  345. this.env = env;
  346. }
  347. /**
  348. * Get the environment attribute.
  349. * @return the environment attribute
  350. * @since Ant 1.5
  351. */
  352. public String getEnvironment() {
  353. return env;
  354. }
  355. /**
  356. * The classpath to use when looking up a resource.
  357. * @param classpath to add to any existing classpath
  358. */
  359. public void setClasspath(Path classpath) {
  360. if (this.classpath == null) {
  361. this.classpath = classpath;
  362. } else {
  363. this.classpath.append(classpath);
  364. }
  365. }
  366. /**
  367. * The classpath to use when looking up a resource.
  368. * @return a path to be configured
  369. */
  370. public Path createClasspath() {
  371. if (this.classpath == null) {
  372. this.classpath = new Path(getProject());
  373. }
  374. return this.classpath.createPath();
  375. }
  376. /**
  377. * the classpath to use when looking up a resource,
  378. * given as reference to a &lt;path&gt; defined elsewhere
  379. * @param r a reference to a classpath
  380. */
  381. public void setClasspathRef(Reference r) {
  382. createClasspath().setRefid(r);
  383. }
  384. /**
  385. * Get the classpath used when looking up a resource.
  386. * @return the classpath
  387. * @since Ant 1.5
  388. */
  389. public Path getClasspath() {
  390. return classpath;
  391. }
  392. /**
  393. * @param userProperty ignored
  394. * @deprecated since 1.5.x.
  395. * This was never a supported feature and has been
  396. * deprecated without replacement.
  397. * @ant.attribute ignore="true"
  398. */
  399. public void setUserProperty(boolean userProperty) {
  400. log("DEPRECATED: Ignoring request to set user property in Property"
  401. + " task.", Project.MSG_WARN);
  402. }
  403. /**
  404. * get the value of this property
  405. * @return the current value or the empty string
  406. */
  407. public String toString() {
  408. return value == null ? "" : value;
  409. }
  410. /**
  411. * set the property in the project to the value.
  412. * if the task was give a file, resource or env attribute
  413. * here is where it is loaded
  414. * @throws BuildException on error
  415. */
  416. public void execute() throws BuildException {
  417. if (getProject() == null) {
  418. throw new IllegalStateException("project has not been set");
  419. }
  420. if (name != null) {
  421. if (untypedValue == null && ref == null) {
  422. throw new BuildException("You must specify value, location or "
  423. + "refid with the name attribute",
  424. getLocation());
  425. }
  426. } else {
  427. if (url == null && file == null && resource == null && env == null) {
  428. throw new BuildException("You must specify url, file, resource or "
  429. + "environment when not using the "
  430. + "name attribute", getLocation());
  431. }
  432. }
  433. if (url == null && file == null && resource == null && prefix != null) {
  434. throw new BuildException("Prefix is only valid when loading from "
  435. + "a url, file or resource", getLocation());
  436. }
  437. if (name != null && untypedValue != null) {
  438. if (relative) {
  439. try {
  440. File from = untypedValue instanceof File ? (File)untypedValue : new File(untypedValue.toString());
  441. File to = basedir != null ? basedir : getProject().getBaseDir();
  442. String relPath = FileUtils.getRelativePath(to, from);
  443. relPath = relPath.replace('/', File.separatorChar);
  444. addProperty(name, relPath);
  445. } catch (Exception e) {
  446. throw new BuildException(e, getLocation());
  447. }
  448. } else {
  449. addProperty(name, untypedValue);
  450. }
  451. }
  452. if (file != null) {
  453. loadFile(file);
  454. }
  455. if (url != null) {
  456. loadUrl(url);
  457. }
  458. if (resource != null) {
  459. loadResource(resource);
  460. }
  461. if (env != null) {
  462. loadEnvironment(env);
  463. }
  464. if ((name != null) && (ref != null)) {
  465. try {
  466. addProperty(name,
  467. ref.getReferencedObject(getProject()).toString());
  468. } catch (BuildException be) {
  469. if (fallback != null) {
  470. addProperty(name,
  471. ref.getReferencedObject(fallback).toString());
  472. } else {
  473. throw be;
  474. }
  475. }
  476. }
  477. }
  478. /**
  479. * load properties from a url
  480. * @param url url to load from
  481. * @throws BuildException on error
  482. */
  483. protected void loadUrl(URL url) throws BuildException {
  484. Properties props = new Properties();
  485. log("Loading " + url, Project.MSG_VERBOSE);
  486. try {
  487. InputStream is = url.openStream();
  488. try {
  489. loadProperties(props, is, url.getFile().endsWith(".xml"));
  490. } finally {
  491. if (is != null) {
  492. is.close();
  493. }
  494. }
  495. addProperties(props);
  496. } catch (IOException ex) {
  497. throw new BuildException(ex, getLocation());
  498. }
  499. }
  500. /**
  501. * Loads the properties defined in the InputStream into the given
  502. * property. On Java5+ it supports reading from XML based property
  503. * definition.
  504. * @param props The property object to load into
  505. * @param is The input stream from where to load
  506. * @param isXml <tt>true</tt> if we should try to load from xml
  507. * @throws IOException if something goes wrong
  508. * @since 1.7.1
  509. * @see http://java.sun.com/dtd/properties.dtd
  510. * @see java.util.Properties#loadFromXML(InputStream)
  511. */
  512. private void loadProperties(
  513. Properties props, InputStream is, boolean isXml) throws IOException {
  514. if (isXml) {
  515. // load the xml based property definition
  516. // use reflection because of bwc to Java 1.4
  517. try {
  518. Method loadXmlMethod = props.getClass().getMethod("loadFromXML",
  519. new Class[] {InputStream.class});
  520. loadXmlMethod.invoke(props, new Object[] {is});
  521. } catch (NoSuchMethodException e) {
  522. e.printStackTrace();
  523. log("Can not load xml based property definition on Java < 5");
  524. } catch (Exception e) {
  525. // no-op
  526. e.printStackTrace();
  527. }
  528. } else {
  529. // load ".properties" format
  530. props.load(is);
  531. }
  532. }
  533. /**
  534. * load properties from a file
  535. * @param file file to load
  536. * @throws BuildException on error
  537. */
  538. protected void loadFile(File file) throws BuildException {
  539. Properties props = new Properties();
  540. log("Loading " + file.getAbsolutePath(), Project.MSG_VERBOSE);
  541. try {
  542. if (file.exists()) {
  543. FileInputStream fis = null;
  544. try {
  545. fis = new FileInputStream(file);
  546. loadProperties(props, fis, file.getName().endsWith(".xml"));
  547. } finally {
  548. FileUtils.close(fis);
  549. }
  550. addProperties(props);
  551. } else {
  552. log("Unable to find property file: " + file.getAbsolutePath(),
  553. Project.MSG_VERBOSE);
  554. }
  555. } catch (IOException ex) {
  556. throw new BuildException(ex, getLocation());
  557. }
  558. }
  559. /**
  560. * load properties from a resource in the current classpath
  561. * @param name name of resource to load
  562. */
  563. protected void loadResource(String name) {
  564. Properties props = new Properties();
  565. log("Resource Loading " + name, Project.MSG_VERBOSE);
  566. InputStream is = null;
  567. ClassLoader cL = null;
  568. boolean cleanup = false;
  569. try {
  570. if (classpath != null) {
  571. cleanup = true;
  572. cL = getProject().createClassLoader(classpath);
  573. } else {
  574. cL = this.getClass().getClassLoader();
  575. }
  576. if (cL == null) {
  577. is = ClassLoader.getSystemResourceAsStream(name);
  578. } else {
  579. is = cL.getResourceAsStream(name);
  580. }
  581. if (is != null) {
  582. loadProperties(props, is, name.endsWith(".xml"));
  583. addProperties(props);
  584. } else {
  585. log("Unable to find resource " + name, Project.MSG_WARN);
  586. }
  587. } catch (IOException ex) {
  588. throw new BuildException(ex, getLocation());
  589. } finally {
  590. if (is != null) {
  591. try {
  592. is.close();
  593. } catch (IOException e) {
  594. // ignore
  595. }
  596. }
  597. if (cleanup && cL != null) {
  598. ((AntClassLoader) cL).cleanup();
  599. }
  600. }
  601. }
  602. /**
  603. * load the environment values
  604. * @param prefix prefix to place before them
  605. */
  606. protected void loadEnvironment(String prefix) {
  607. Properties props = new Properties();
  608. if (!prefix.endsWith(".")) {
  609. prefix += ".";
  610. }
  611. log("Loading Environment " + prefix, Project.MSG_VERBOSE);
  612. Map osEnv = Execute.getEnvironmentVariables();
  613. for (Iterator e = osEnv.entrySet().iterator(); e.hasNext(); ) {
  614. Map.Entry entry = (Map.Entry) e.next();
  615. props.put(prefix + entry.getKey(), entry.getValue());
  616. }
  617. addProperties(props);
  618. }
  619. /**
  620. * iterate through a set of properties,
  621. * resolve them then assign them
  622. * @param props the properties to iterate over
  623. */
  624. protected void addProperties(Properties props) {
  625. HashMap m = new HashMap(props);
  626. resolveAllProperties(m);
  627. for (Iterator it = m.keySet().iterator(); it.hasNext();) {
  628. Object k = it.next();
  629. if (k instanceof String) {
  630. String propertyName = (String) k;
  631. if (prefix != null) {
  632. propertyName = prefix + propertyName;
  633. }
  634. addProperty(propertyName, m.get(k));
  635. }
  636. }
  637. }
  638. /**
  639. * add a name value pair to the project property set
  640. * @param n name of property
  641. * @param v value to set
  642. */
  643. protected void addProperty(String n, String v) {
  644. addProperty(n, (Object) v);
  645. }
  646. /**
  647. * add a name value pair to the project property set
  648. * @param n name of property
  649. * @param v value to set
  650. * @since Ant 1.8
  651. */
  652. protected void addProperty(String n, Object v) {
  653. PropertyHelper ph = PropertyHelper.getPropertyHelper(getProject());
  654. if (userProperty) {
  655. if (ph.getUserProperty(n) == null) {
  656. ph.setInheritedProperty(n, v);
  657. } else {
  658. log("Override ignored for " + n, Project.MSG_VERBOSE);
  659. }
  660. } else {
  661. ph.setNewProperty(n, v);
  662. }
  663. }
  664. /**
  665. * resolve properties inside a properties hashtable
  666. * @param props properties object to resolve
  667. */
  668. private void resolveAllProperties(Map props) throws BuildException {
  669. PropertyHelper propertyHelper
  670. = (PropertyHelper) PropertyHelper.getPropertyHelper(getProject());
  671. new ResolvePropertyMap(
  672. getProject(),
  673. propertyHelper,
  674. propertyHelper.getExpanders())
  675. .resolveAllProperties(props, getPrefix(), getPrefixValues());
  676. }
  677. }