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.

Tstamp.java 14 kB

8 years ago
11 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388
  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. * https://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.text.SimpleDateFormat;
  20. import java.time.Instant;
  21. import java.util.Calendar;
  22. import java.util.Date;
  23. import java.util.HashMap;
  24. import java.util.List;
  25. import java.util.Locale;
  26. import java.util.Map;
  27. import java.util.NoSuchElementException;
  28. import java.util.Optional;
  29. import java.util.StringTokenizer;
  30. import java.util.TimeZone;
  31. import java.util.Vector;
  32. import java.util.function.BiFunction;
  33. import java.util.function.Function;
  34. import org.apache.tools.ant.BuildException;
  35. import org.apache.tools.ant.Location;
  36. import org.apache.tools.ant.MagicNames;
  37. import org.apache.tools.ant.Project;
  38. import org.apache.tools.ant.Task;
  39. import org.apache.tools.ant.types.EnumeratedAttribute;
  40. /**
  41. * Sets properties to the current time, or offsets from the current time.
  42. * The default properties are TSTAMP, DSTAMP and TODAY;
  43. *
  44. * @since Ant 1.1
  45. * @ant.task category="utility"
  46. */
  47. public class Tstamp extends Task {
  48. private static final String ENV_SOURCE_DATE_EPOCH = "SOURCE_DATE_EPOCH";
  49. private List<CustomFormat> customFormats = new Vector<>();
  50. private String prefix = "";
  51. /**
  52. * Set a prefix for the properties. If the prefix does not end with a "."
  53. * one is automatically added.
  54. * @param prefix the prefix to use.
  55. * @since Ant 1.5
  56. */
  57. public void setPrefix(String prefix) {
  58. this.prefix = prefix;
  59. if (!this.prefix.endsWith(".")) {
  60. this.prefix += ".";
  61. }
  62. }
  63. /**
  64. * create the timestamps. Custom ones are done before
  65. * the standard ones, to get their retaliation in early.
  66. * @throws BuildException on error.
  67. */
  68. @Override
  69. public void execute() throws BuildException {
  70. try {
  71. Date d = getNow();
  72. // Honour reproducible builds https://reproducible-builds.org/specs/source-date-epoch/#idm55
  73. final String epoch = System.getenv(ENV_SOURCE_DATE_EPOCH);
  74. try {
  75. if (epoch != null) {
  76. // Value of SOURCE_DATE_EPOCH will be an integer, representing seconds.
  77. d = new Date(Integer.parseInt(epoch) * 1000);
  78. }
  79. log("Honouring environment variable " + ENV_SOURCE_DATE_EPOCH + " which has been set to " + epoch);
  80. } catch(NumberFormatException e) {
  81. // ignore
  82. log("Ignoring invalid value '" + epoch + "' for " + ENV_SOURCE_DATE_EPOCH
  83. + " environment variable", Project.MSG_DEBUG);
  84. }
  85. final Date date = d;
  86. customFormats.forEach(cts -> cts.execute(getProject(), date, getLocation()));
  87. SimpleDateFormat dstamp = new SimpleDateFormat("yyyyMMdd");
  88. setProperty("DSTAMP", dstamp.format(d));
  89. SimpleDateFormat tstamp = new SimpleDateFormat("HHmm");
  90. setProperty("TSTAMP", tstamp.format(d));
  91. SimpleDateFormat today
  92. = new SimpleDateFormat("MMMM d yyyy", Locale.US);
  93. setProperty("TODAY", today.format(d));
  94. } catch (Exception e) {
  95. throw new BuildException(e);
  96. }
  97. }
  98. /**
  99. * create a custom format with the current prefix.
  100. * @return a ready to fill-in format
  101. */
  102. public CustomFormat createFormat() {
  103. CustomFormat cts = new CustomFormat();
  104. customFormats.add(cts);
  105. return cts;
  106. }
  107. /**
  108. * helper that encapsulates prefix logic and property setting
  109. * policy (i.e. we use setNewProperty instead of setProperty).
  110. */
  111. private void setProperty(String name, String value) {
  112. getProject().setNewProperty(prefix + name, value);
  113. }
  114. /**
  115. * Return the {@link Date} instance to use as base for DSTAMP, TSTAMP and TODAY.
  116. *
  117. * @return Date
  118. */
  119. protected Date getNow() {
  120. Optional<Date> now = getNow(
  121. MagicNames.TSTAMP_NOW_ISO,
  122. s -> Date.from(Instant.parse(s)),
  123. (k, v) -> "magic property " + k + " ignored as '" + v + "' is not in valid ISO pattern"
  124. );
  125. if (now.isPresent()) {
  126. return now.get();
  127. }
  128. now = getNow(
  129. MagicNames.TSTAMP_NOW,
  130. s -> new Date(1000 * Long.parseLong(s)),
  131. (k, v) -> "magic property " + k + " ignored as " + v + " is not a valid number"
  132. );
  133. return now.orElseGet(Date::new);
  134. }
  135. /**
  136. * Checks and returns a Date if the specified property is set.
  137. * @param propertyName name of the property to check
  138. * @param map conversion of the property value as string to Date
  139. * @param log supplier of the log message containing the property name and value if
  140. * the conversion fails
  141. * @return Optional containing the Date or null
  142. */
  143. protected Optional<Date> getNow(String propertyName, Function<String, Date> map, BiFunction<String, String, String> log) {
  144. String property = getProject().getProperty(propertyName);
  145. if (property != null && !property.isEmpty()) {
  146. try {
  147. return Optional.ofNullable(map.apply(property));
  148. } catch (Exception e) {
  149. log(log.apply(propertyName, property));
  150. }
  151. }
  152. return Optional.empty();
  153. }
  154. /**
  155. * This nested element that allows a property to be set
  156. * to the current date and time in a given format.
  157. * The date/time patterns are as defined in the
  158. * Java SimpleDateFormat class.
  159. * The format element also allows offsets to be applied to
  160. * the time to generate different time values.
  161. * @todo consider refactoring out into a re-usable element.
  162. */
  163. public class CustomFormat {
  164. private TimeZone timeZone;
  165. private String propertyName;
  166. private String pattern;
  167. private String language;
  168. private String country;
  169. private String variant;
  170. private int offset = 0;
  171. private int field = Calendar.DATE;
  172. /**
  173. * The property to receive the date/time string in the given pattern
  174. * @param propertyName the name of the property.
  175. */
  176. public void setProperty(String propertyName) {
  177. this.propertyName = propertyName;
  178. }
  179. /**
  180. * The date/time pattern to be used. The values are as
  181. * defined by the Java SimpleDateFormat class.
  182. * @param pattern the pattern to use.
  183. * @see java.text.SimpleDateFormat
  184. */
  185. public void setPattern(String pattern) {
  186. this.pattern = pattern;
  187. }
  188. /**
  189. * The locale used to create date/time string.
  190. * The general form is "language, country, variant" but
  191. * either variant or variant and country may be omitted.
  192. * For more information please refer to documentation
  193. * for the java.util.Locale class.
  194. * @param locale the locale to use.
  195. * @see java.util.Locale
  196. */
  197. public void setLocale(String locale) {
  198. StringTokenizer st = new StringTokenizer(locale, " \t\n\r\f,");
  199. try {
  200. language = st.nextToken();
  201. if (st.hasMoreElements()) {
  202. country = st.nextToken();
  203. if (st.hasMoreElements()) {
  204. variant = st.nextToken();
  205. if (st.hasMoreElements()) {
  206. throw new BuildException("bad locale format", getLocation());
  207. }
  208. }
  209. } else {
  210. country = "";
  211. }
  212. } catch (NoSuchElementException e) {
  213. throw new BuildException("bad locale format", e, getLocation());
  214. }
  215. }
  216. /**
  217. * The timezone to use for displaying time.
  218. * The values are as defined by the Java TimeZone class.
  219. * @param id the timezone value.
  220. * @see java.util.TimeZone
  221. */
  222. public void setTimezone(String id) {
  223. timeZone = TimeZone.getTimeZone(id);
  224. }
  225. /**
  226. * The numeric offset to the current time.
  227. * @param offset the offset to use.
  228. */
  229. public void setOffset(int offset) {
  230. this.offset = offset;
  231. }
  232. /**
  233. * Set the unit type (using String).
  234. * @param unit the unit to use.
  235. * @deprecated since 1.5.x.
  236. * setUnit(String) is deprecated and is replaced with
  237. * setUnit(Tstamp.Unit) to make Ant's
  238. * Introspection mechanism do the work and also to
  239. * encapsulate operations on the unit in its own
  240. * class.
  241. */
  242. @Deprecated
  243. public void setUnit(String unit) {
  244. log("DEPRECATED - The setUnit(String) method has been deprecated. Use setUnit(Tstamp.Unit) instead.");
  245. Unit u = new Unit();
  246. u.setValue(unit);
  247. field = u.getCalendarField();
  248. }
  249. /**
  250. * The unit of the offset to be applied to the current time.
  251. * Valid Values are
  252. * <ul>
  253. * <li>millisecond</li>
  254. * <li>second</li>
  255. * <li>minute</li>
  256. * <li>hour</li>
  257. * <li>day</li>
  258. * <li>week</li>
  259. * <li>month</li>
  260. * <li>year</li>
  261. * </ul>
  262. * The default unit is day.
  263. * @param unit the unit to use.
  264. */
  265. public void setUnit(Unit unit) {
  266. field = unit.getCalendarField();
  267. }
  268. /**
  269. * validate parameter and execute the format.
  270. * @param project project to set property in.
  271. * @param date date to use as a starting point.
  272. * @param location line in file (for errors)
  273. */
  274. public void execute(Project project, Date date, Location location) {
  275. if (propertyName == null) {
  276. throw new BuildException("property attribute must be provided", location);
  277. }
  278. if (pattern == null) {
  279. throw new BuildException("pattern attribute must be provided", location);
  280. }
  281. SimpleDateFormat sdf;
  282. if (language == null) {
  283. sdf = new SimpleDateFormat(pattern);
  284. } else if (variant == null) {
  285. sdf = new SimpleDateFormat(pattern, new Locale(language, country));
  286. } else {
  287. sdf = new SimpleDateFormat(pattern, new Locale(language, country, variant));
  288. }
  289. if (offset != 0) {
  290. Calendar calendar = Calendar.getInstance();
  291. calendar.setTime(date);
  292. calendar.add(field, offset);
  293. date = calendar.getTime();
  294. }
  295. if (timeZone != null) {
  296. sdf.setTimeZone(timeZone);
  297. }
  298. Tstamp.this.setProperty(propertyName, sdf.format(date));
  299. }
  300. }
  301. /**
  302. * set of valid units to use for time offsets.
  303. */
  304. public static class Unit extends EnumeratedAttribute {
  305. private static final String MILLISECOND = "millisecond";
  306. private static final String SECOND = "second";
  307. private static final String MINUTE = "minute";
  308. private static final String HOUR = "hour";
  309. private static final String DAY = "day";
  310. private static final String WEEK = "week";
  311. private static final String MONTH = "month";
  312. private static final String YEAR = "year";
  313. private static final String[] UNITS = {
  314. MILLISECOND,
  315. SECOND,
  316. MINUTE,
  317. HOUR,
  318. DAY,
  319. WEEK,
  320. MONTH,
  321. YEAR
  322. };
  323. private Map<String, Integer> calendarFields = new HashMap<>();
  324. /** Constructor for Unit enumerated type. */
  325. public Unit() {
  326. calendarFields.put(MILLISECOND,
  327. Calendar.MILLISECOND);
  328. calendarFields.put(SECOND, Calendar.SECOND);
  329. calendarFields.put(MINUTE, Calendar.MINUTE);
  330. calendarFields.put(HOUR, Calendar.HOUR_OF_DAY);
  331. calendarFields.put(DAY, Calendar.DATE);
  332. calendarFields.put(WEEK, Calendar.WEEK_OF_YEAR);
  333. calendarFields.put(MONTH, Calendar.MONTH);
  334. calendarFields.put(YEAR, Calendar.YEAR);
  335. }
  336. /**
  337. * Convert the value to int unit value.
  338. * @return an int value.
  339. */
  340. public int getCalendarField() {
  341. String key = getValue().toLowerCase(Locale.ENGLISH);
  342. return calendarFields.get(key);
  343. }
  344. /**
  345. * Get the valid values.
  346. * @return the value values.
  347. */
  348. @Override
  349. public String[] getValues() {
  350. return UNITS;
  351. }
  352. }
  353. }