KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > idaremedia > antx > valueuri > datetime > DateTimeValueURIHandler


1 /**
2  * $Id: DateTimeValueURIHandler.java 180 2007-03-15 12:56:38Z ssmc $
3  * Copyright 2004-2005 iDare Media, Inc. All rights reserved.
4  *
5  * Originally written by iDare Media, Inc. for release into the public domain. This
6  * library, source form and binary form, is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public License (LGPL) as published
8  * by the Free Software Foundation; either version 2.1 of the License, or (at your option)
9  * any later version.<p>
10  *
11  * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
12  * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
13  * See the GNU LGPL for more details.<p>
14  *
15  * You should have received a copy of the GNU Lesser General Public License along with this
16  * library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite
17  * 330, Boston, MA 02111-1307 USA. The GNU LGPL can be found online at
18  * http://www.fsf.org/copyleft/lesser.html<p>
19  *
20  * This product has been influenced by several projects within the open-source community.
21  * The JWare developers wish to acknowledge the open-source community's support. For more
22  * information regarding the open-source products used within JWare, please visit the
23  * JWare website.
24  *----------------------------------------------------------------------------------------*
25  * WEBSITE- http://www.jware.info EMAIL- inquiries@jware.info
26  *----------------------------------------------------------------------------------------*
27  **/

28
29 package com.idaremedia.antx.valueuri.datetime;
30
31 import java.text.Format JavaDoc;
32 import java.text.SimpleDateFormat JavaDoc;
33 import java.util.Map JavaDoc;
34
35 import org.apache.tools.ant.Project;
36
37 import com.idaremedia.antx.AntX;
38 import com.idaremedia.antx.AntXFixture;
39 import com.idaremedia.antx.ValueURIHandler;
40 import com.idaremedia.antx.apis.Requester;
41 import com.idaremedia.antx.helpers.DateTimeFormat;
42 import com.idaremedia.antx.helpers.DurationFormat;
43 import com.idaremedia.antx.helpers.Tk;
44
45 /**
46  * Value URI handler that converts simple datetime queries into formatted
47  * date/time strings. In addition to the symbolic format (the protocol's name),
48  * you must specify the timestamp in one of three ways: use the string "now" for
49  * the current system time, using piped result of another value uri, or declare the
50  * timestamp number value itself as a string.
51  * <p/>
52  * To specify a custom format string use the value URI fragment bits after the
53  * "&#63;" like: <span class="src">${$PS:now?'['h:mm:ss']$ '}</span>.
54  * <p/>
55  * <b>Example Usage:</b><pre>
56  * &lt;echo message="Current time is: ${$shorttime:now}"/&gt;
57  * &lt;echo message="Current GMT time is: ${$gmtdatetime:now}"/&gt;
58  *
59  * &lt;echo message="My time prompt: ${$prompt:now?'['h:mm:ss']: '}"/&gt;
60  *
61  * &lt;assign var="starttime" op="now"/&gt;
62  * &lt;show msgid="start.work.at" msgarg1="${$var:starttime|$datetime:}"/&gt;
63  * ...<i>[work work work]</i>
64  * &lt;show msgid="ended.work.at" msgarg1="${$datetime:}"/&gt;
65  *
66  * &lt;assign var="timing" op="now"/&gt;
67  * ...<i>[work work work]</i>
68  * &lt;assign var="timing" op="-now"/&gt;
69  * &lt;echo message="It Took: ${$var:timing|$duration:}"/&gt;
70  *
71  * -- To Install --
72  * &lt;manageuris action="install"&gt;
73  * &lt;parameter name="datetime"
74  * value="com.idaremedia.antx.valueuri.DateTimeValueURIHandler"/&gt;
75  * &lt;parameter name="shortdatetime"
76  * value="com.idaremedia.antx.valueuri.DateTimeValueURIHandler"/&gt;
77  * ...<i>[All other standard names and your own custom ones if desired]</i>
78  * &lt;/manageuris&gt;
79  * </pre>
80  *
81  * @since JWare/AntX 0.5
82  * @author ssmc, &copy;2004-2005 <a HREF="http://www.jware.info">iDare&nbsp;Media,&nbsp;Inc.</a>
83  * @version 0.5
84  * @.safety multiple
85  * @.group api,helper
86  * @.caveat You must use one of the expected scheme names to get the default
87  * formats; otherwise you must manually map your scheme name to this
88  * handler and <em>always</em> provide a format string.
89  **/

90
91 public final class DateTimeValueURIHandler implements ValueURIHandler
92 {
93     private static final Map JavaDoc LINKS = AntXFixture.newMap();
94     static {
95         //NB: long-winded and uglee but obvious. Also not
96
// likely to change anytime soon...
97
LINKS.put("$longdatetime:",DateTimeFormat.STANDARD);
98         LINKS.put("$longtime:",DateTimeFormat.STANDARD_TIME);
99         LINKS.put("$longdate:",DateTimeFormat.STANDARD_DATE);
100         LINKS.put("$gmtdatetime:",DateTimeFormat.GMT);
101         LINKS.put("$gmtdate:",DateTimeFormat.GMT_DATE);
102         LINKS.put("$gmttime:",DateTimeFormat.GMT_TIME);
103         LINKS.put("$shortdatetime:",DateTimeFormat.ABBREV);
104         LINKS.put("$shorttime:",DateTimeFormat.ABBREV_TIME);
105         LINKS.put("$shortdate:",DateTimeFormat.ABBREV_DATE);
106         LINKS.put("$datetime:",DateTimeFormat.STANDARD);
107         LINKS.put("$time:",DateTimeFormat.STANDARD_TIME);
108         LINKS.put("$date:",DateTimeFormat.STANDARD_DATE);
109         LINKS.put("$duration:",DurationFormat.INSTANCE);
110         LINKS.put("$changelogdate:",DateTimeFormat.CHANGELOG);
111         LINKS.put("$cvsdate:",DateTimeFormat.CHANGELOG);
112         LINKS.put("$svndate:",DateTimeFormat.CHANGELOG);
113     }
114
115
116
117     /**
118      * Initializes a new datetime value uri handler.
119      **/

120     public DateTimeValueURIHandler()
121     {
122     }
123  
124  
125
126     /**
127      * Returns the best fit formatter for the format directive
128      * embedded in a given date value uri.
129      * @param fullUri the full uri (including the '$protocol:' prefix)
130      * @param clnt problem handler (non-null)
131      * @return the formatter or <i>null</i> if no match found.
132      **/

133     public static Format JavaDoc defaultFormatter(String JavaDoc fullUri, Requester clnt)
134     {
135         Format JavaDoc dfmt= null;
136         int i= fullUri.indexOf(':');
137         if (i>0) {
138             String JavaDoc which= fullUri.substring(0,++i);
139             dfmt = (Format JavaDoc)LINKS.get(which);
140             if (dfmt==null && (i=fullUri.indexOf("?",i))>0) {
141                 i++;
142                 if (i<fullUri.length()-1) {
143                     String JavaDoc fmtstr = fullUri.substring(i);
144                     fmtstr = Tk.resolveString(clnt.getProject(),fmtstr,true);
145                     try {
146                         dfmt = new SimpleDateFormat JavaDoc(fmtstr);
147                     } catch(IllegalArgumentException JavaDoc mfX) {
148                         clnt.problem(mfX.getMessage(),Project.MSG_WARN);
149                     }
150                 }
151             }
152         }
153         return dfmt;
154     }
155
156
157
158     /**
159      * Returns a snapshot of the current set of uri scheme name to
160      * format mappings. Never returns <i>null</i>. The returned map
161      * is disassociated from this class; modifications to it are not
162      * reflected back to this class.
163      * @.impl Used for testing this class.
164      **/

165     public static Map JavaDoc copyOfMappings()
166     {
167         synchronized(LINKS) {
168             return AntXFixture.newMapCopy(LINKS);
169         }
170     }
171
172
173
174     /**
175      * Tries to determine if the named scheme is a timestamp based
176      * format or a duration format. Duration formats expect delta
177      * for the timestamp parameter; timestamp format expect well
178      * timestamps.
179      * @param scheme name of uri scheme
180      * @return Boolean.TRUE or Boolean.FALSE if can determine one
181      * way or other from name; otherwise returns <i>null</i>.
182      **/

183     public static Boolean JavaDoc isTimestampScheme(String JavaDoc scheme)
184     {
185         Boolean JavaDoc yes = null;
186         if (scheme!=null) {
187             scheme = Tk.lowercaseFrom(scheme);
188             if (scheme.indexOf("date")>=0 || scheme.indexOf("time")>=0) {
189                 yes = Boolean.TRUE;
190             } else if (scheme.indexOf("duration")>=0) {
191                 yes = Boolean.FALSE;
192             }
193         }
194         return yes;
195     }
196
197
198
199     /**
200      * Utility to format the given timestamp according a date value
201      * uri format directive.
202      * @param time the timestamp to use
203      * @param fullUri the format informaton uri (non-null)
204      * @param clnt problem handler (non-null)
205      * @return formatted string or <i>null</i> if no formatter
206      * match found.
207      **/

208     public String JavaDoc format(long time, String JavaDoc fullUri, Requester clnt)
209     {
210         Format JavaDoc dfmt= defaultFormatter(fullUri,clnt);
211         if (dfmt!=null) {
212             return DateTimeFormat.format(time,dfmt);
213         }
214         return null;
215     }
216
217
218
219     /**
220      * Returns a formatted datetime string for "now" uri. Any
221      * other timestamp returns <i>null</i>.
222      **/

223     public String JavaDoc getDefaultValue(String JavaDoc fullUri, Requester clnt)
224     {
225         final long NOW = now();
226         if (fullUri.endsWith(":now")) {
227             return format(NOW,fullUri,clnt);
228         }
229         if (fullUri.indexOf(":now?")>1) {
230             return format(NOW,fullUri,clnt);
231         }
232         return null;
233     }
234
235
236
237     /**
238      * The uri fragment can be one of three things: either the string
239      * "now" for the current system time, or a <em>single</em> redirect
240      * to a reference or variable that contains the timestamp, or the
241      * timestamp value itself as a string.
242      **/

243     public String JavaDoc valueFrom(String JavaDoc uriFragment, String JavaDoc fullUri, Requester clnt)
244     {
245         String JavaDoc timestring = uriFragment;
246         int i = uriFragment.indexOf('?');
247         if (i>=0) {
248             timestring = uriFragment.substring(0,i++);
249         }
250         timestring = Tk.resolveString(clnt.getProject(),timestring,true);
251
252         if (timestring.length()==0 || "now".equals(timestring)) {
253             return format(now(),fullUri,clnt);
254         }
255
256         long timestamp = Tk.longFrom(timestring,-1L);
257         if (timestamp>0L) {
258             return format(timestamp,fullUri,clnt);
259         }
260
261         return null;
262     }
263
264
265     /**
266      * Tells this handler what "now" means. Never used from live uri
267      * handling mechanism; only for testing and stubs.
268      * @param timestamp the required value of "now" (>=0L)
269      * @.impl Used for testing this class.
270      **/

271     public void setNow(long timestamp)
272     {
273         AntX.require_(timestamp>=0L,AntX.utilities+"DateTimeValueURIHandler:",
274                       "setnow- valid timstamp");
275         m_nowTS = timestamp;
276     }
277
278
279     private long now()
280     {
281         return m_nowTS<0L ? System.currentTimeMillis() : m_nowTS;
282     }
283
284
285     private long m_nowTS = -1L;
286 }
287
288 /* end-of-DateTimeValueURIHandler.java */
Popular Tags