KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > tools > ant > taskdefs > Tstamp


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
19 package org.apache.tools.ant.taskdefs;
20
21 import java.text.SimpleDateFormat JavaDoc;
22 import java.util.Calendar JavaDoc;
23 import java.util.Date JavaDoc;
24 import java.util.Enumeration JavaDoc;
25 import java.util.HashMap JavaDoc;
26 import java.util.Locale JavaDoc;
27 import java.util.Map JavaDoc;
28 import java.util.NoSuchElementException JavaDoc;
29 import java.util.StringTokenizer JavaDoc;
30 import java.util.TimeZone JavaDoc;
31 import java.util.Vector JavaDoc;
32 import org.apache.tools.ant.BuildException;
33 import org.apache.tools.ant.Location;
34 import org.apache.tools.ant.Project;
35 import org.apache.tools.ant.Task;
36 import org.apache.tools.ant.types.EnumeratedAttribute;
37
38 /**
39  * Sets properties to the current time, or offsets from the current time.
40  * The default properties are TSTAMP, DSTAMP and TODAY;
41  *
42  * @since Ant 1.1
43  * @ant.task category="utility"
44  */

45 public class Tstamp extends Task {
46
47     private Vector JavaDoc customFormats = new Vector JavaDoc();
48     private String JavaDoc prefix = "";
49
50     /**
51      * Set a prefix for the properties. If the prefix does not end with a "."
52      * one is automatically added.
53      * @param prefix the prefix to use.
54      * @since Ant 1.5
55      */

56     public void setPrefix(String JavaDoc prefix) {
57         this.prefix = prefix;
58         if (!this.prefix.endsWith(".")) {
59             this.prefix += ".";
60         }
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     public void execute() throws BuildException {
69         try {
70             Date JavaDoc d = new Date JavaDoc();
71
72             Enumeration JavaDoc i = customFormats.elements();
73             while (i.hasMoreElements()) {
74                 CustomFormat cts = (CustomFormat) i.nextElement();
75                 cts.execute(getProject(), d, getLocation());
76             }
77
78             SimpleDateFormat JavaDoc dstamp = new SimpleDateFormat JavaDoc ("yyyyMMdd");
79             setProperty("DSTAMP", dstamp.format(d));
80
81             SimpleDateFormat JavaDoc tstamp = new SimpleDateFormat JavaDoc ("HHmm");
82             setProperty("TSTAMP", tstamp.format(d));
83
84             SimpleDateFormat JavaDoc today
85                 = new SimpleDateFormat JavaDoc ("MMMM d yyyy", Locale.US);
86             setProperty("TODAY", today.format(d));
87
88         } catch (Exception JavaDoc e) {
89             throw new BuildException(e);
90         }
91     }
92
93     /**
94      * create a custom format with the current prefix.
95      * @return a ready to fill-in format
96      */

97     public CustomFormat createFormat() {
98         CustomFormat cts = new CustomFormat();
99         customFormats.addElement(cts);
100         return cts;
101     }
102
103     /**
104      * helper that encapsulates prefix logic and property setting
105      * policy (i.e. we use setNewProperty instead of setProperty).
106      */

107     private void setProperty(String JavaDoc name, String JavaDoc value) {
108         getProject().setNewProperty(prefix + name, value);
109     }
110
111     /**
112      * This nested element that allows a property to be set
113      * to the current date and time in a given format.
114      * The date/time patterns are as defined in the
115      * Java SimpleDateFormat class.
116      * The format element also allows offsets to be applied to
117      * the time to generate different time values.
118      * @todo consider refactoring out into a re-usable element.
119      */

120     public class CustomFormat {
121         private TimeZone JavaDoc timeZone;
122         private String JavaDoc propertyName;
123         private String JavaDoc pattern;
124         private String JavaDoc language;
125         private String JavaDoc country;
126         private String JavaDoc variant;
127         private int offset = 0;
128         private int field = Calendar.DATE;
129
130         /**
131          * Create a format
132          */

133         public CustomFormat() {
134         }
135
136         /**
137          * The property to receive the date/time string in the given pattern
138          * @param propertyName the name of the property.
139          */

140         public void setProperty(String JavaDoc propertyName) {
141             this.propertyName = propertyName;
142         }
143
144         /**
145          * The date/time pattern to be used. The values are as
146          * defined by the Java SimpleDateFormat class.
147          * @param pattern the pattern to use.
148          * @see java.text.SimpleDateFormat
149          */

150         public void setPattern(String JavaDoc pattern) {
151             this.pattern = pattern;
152         }
153
154         /**
155          * The locale used to create date/time string.
156          * The general form is "language, country, variant" but
157          * either variant or variant and country may be omitted.
158          * For more information please refer to documentation
159          * for the java.util.Locale class.
160          * @param locale the locale to use.
161          * @see java.util.Locale
162          */

163         public void setLocale(String JavaDoc locale) {
164             StringTokenizer JavaDoc st = new StringTokenizer JavaDoc(locale, " \t\n\r\f,");
165             try {
166                 language = st.nextToken();
167                 if (st.hasMoreElements()) {
168                     country = st.nextToken();
169                     if (st.hasMoreElements()) {
170                         variant = st.nextToken();
171                         if (st.hasMoreElements()) {
172                             throw new BuildException("bad locale format",
173                                                       getLocation());
174                         }
175                     }
176                 } else {
177                     country = "";
178                 }
179             } catch (NoSuchElementException JavaDoc e) {
180                 throw new BuildException("bad locale format", e,
181                                          getLocation());
182             }
183         }
184
185         /**
186          * The timezone to use for displaying time.
187          * The values are as defined by the Java TimeZone class.
188          * @param id the timezone value.
189          * @see java.util.TimeZone
190          */

191         public void setTimezone(String JavaDoc id) {
192             timeZone = TimeZone.getTimeZone(id);
193         }
194
195         /**
196          * The numeric offset to the current time.
197          * @param offset the offset to use.
198          */

199         public void setOffset(int offset) {
200             this.offset = offset;
201         }
202
203         /**
204          * Set the unit type (using String).
205          * @param unit the unit to use.
206          * @deprecated since 1.5.x.
207          * setUnit(String) is deprecated and is replaced with
208          * setUnit(Tstamp.Unit) to make Ant's
209          * Introspection mechanism do the work and also to
210          * encapsulate operations on the unit in its own
211          * class.
212          */

213         public void setUnit(String JavaDoc unit) {
214             log("DEPRECATED - The setUnit(String) method has been deprecated."
215                 + " Use setUnit(Tstamp.Unit) instead.");
216             Unit u = new Unit();
217             u.setValue(unit);
218             field = u.getCalendarField();
219         }
220
221         /**
222          * The unit of the offset to be applied to the current time.
223          * Valid Values are
224          * <ul>
225          * <li>millisecond</li>
226          * <li>second</li>
227          * <li>minute</li>
228          * <li>hour</li>
229          * <li>day</li>
230          * <li>week</li>
231          * <li>month</li>
232          * <li>year</li>
233          * </ul>
234          * The default unit is day.
235          * @param unit the unit to use.
236          */

237         public void setUnit(Unit unit) {
238             field = unit.getCalendarField();
239         }
240
241         /**
242          * validate parameter and execute the format.
243          * @param project project to set property in.
244          * @param date date to use as a starting point.
245          * @param location line in file (for errors)
246          */

247         public void execute(Project project, Date JavaDoc date, Location location) {
248             if (propertyName == null) {
249                 throw new BuildException("property attribute must be provided",
250                                          location);
251             }
252
253             if (pattern == null) {
254                 throw new BuildException("pattern attribute must be provided",
255                                          location);
256             }
257
258             SimpleDateFormat JavaDoc sdf;
259             if (language == null) {
260                 sdf = new SimpleDateFormat JavaDoc(pattern);
261             } else if (variant == null) {
262                 sdf = new SimpleDateFormat JavaDoc(pattern,
263                                            new Locale JavaDoc(language, country));
264             } else {
265                 sdf = new SimpleDateFormat JavaDoc(pattern,
266                                            new Locale JavaDoc(language, country,
267                                                       variant));
268             }
269             if (offset != 0) {
270                 Calendar JavaDoc calendar = Calendar.getInstance();
271                 calendar.setTime(date);
272                 calendar.add(field, offset);
273                 date = calendar.getTime();
274             }
275             if (timeZone != null) {
276                 sdf.setTimeZone(timeZone);
277             }
278             Tstamp.this.setProperty(propertyName, sdf.format(date));
279         }
280     }
281
282     /**
283      * set of valid units to use for time offsets.
284      */

285     public static class Unit extends EnumeratedAttribute {
286
287         private static final String JavaDoc MILLISECOND = "millisecond";
288         private static final String JavaDoc SECOND = "second";
289         private static final String JavaDoc MINUTE = "minute";
290         private static final String JavaDoc HOUR = "hour";
291         private static final String JavaDoc DAY = "day";
292         private static final String JavaDoc WEEK = "week";
293         private static final String JavaDoc MONTH = "month";
294         private static final String JavaDoc YEAR = "year";
295
296         private static final String JavaDoc[] UNITS = {
297                                                 MILLISECOND,
298                                                 SECOND,
299                                                 MINUTE,
300                                                 HOUR,
301                                                 DAY,
302                                                 WEEK,
303                                                 MONTH,
304                                                 YEAR
305                                               };
306
307         private Map JavaDoc calendarFields = new HashMap JavaDoc();
308
309         /** Constructor for Unit enumerated type. */
310         public Unit() {
311             calendarFields.put(MILLISECOND,
312                                new Integer JavaDoc(Calendar.MILLISECOND));
313             calendarFields.put(SECOND, new Integer JavaDoc(Calendar.SECOND));
314             calendarFields.put(MINUTE, new Integer JavaDoc(Calendar.MINUTE));
315             calendarFields.put(HOUR, new Integer JavaDoc(Calendar.HOUR_OF_DAY));
316             calendarFields.put(DAY, new Integer JavaDoc(Calendar.DATE));
317             calendarFields.put(WEEK, new Integer JavaDoc(Calendar.WEEK_OF_YEAR));
318             calendarFields.put(MONTH, new Integer JavaDoc(Calendar.MONTH));
319             calendarFields.put(YEAR, new Integer JavaDoc(Calendar.YEAR));
320         }
321
322         /**
323          * Convert the value to int unit value.
324          * @return an int value.
325          */

326         public int getCalendarField() {
327             String JavaDoc key = getValue().toLowerCase();
328             Integer JavaDoc i = (Integer JavaDoc) calendarFields.get(key);
329             return i.intValue();
330         }
331
332         /**
333          * Get the valid values.
334          * @return the value values.
335          */

336         public String JavaDoc[] getValues() {
337             return UNITS;
338         }
339     }
340 }
341
Popular Tags