Debian Codegraph @

src/com/adobe/internal/xmp/impl/ISO8601Converter.java

raw symbols SCIP
1 // =================================================================================================
2 // ADOBE SYSTEMS INCORPORATED
3 // Copyright 2006 Adobe Systems Incorporated
4 // All Rights Reserved
5 //
6 // NOTICE: Adobe permits you to use, modify, and distribute this file in accordance with the terms
7 // of the Adobe license agreement accompanying it.
8 // =================================================================================================
9
10 package com.adobe.internal.xmp.impl;
11
12 import java.text.DecimalFormat;
13 import java.text.DecimalFormatSymbols;
14 import java.util.Locale;
15 import java.util.SimpleTimeZone;
16
17 import com.adobe.internal.xmp.XMPDateTime;
18 import com.adobe.internal.xmp.XMPError;
19 import com.adobe.internal.xmp.XMPException;
20
21
22 /**
23 * Converts between ISO 8601 Strings and <code>Calendar</code> with millisecond resolution.
24 *
25 * @author Stefan Makswit
26 * @version $Revision$
27 * @since 16.02.2006
28 */
29 public final class ISO8601Converter
30 {
31 /** Hides public constructor */
32 private ISO8601Converter()
33 {
34 // EMPTY
35 }
36
37
38 /**
39 * Converts an ISO 8601 string to an <code>XMPDateTime</code>.
40 *
41 * Parse a date according to ISO 8601 and
42 * http://www.w3.org/TR/NOTE-datetime:
43 * <ul>
44 * <li>YYYY
45 * <li>YYYY-MM
46 * <li>YYYY-MM-DD
47 * <li>YYYY-MM-DDThh:mmTZD
48 * <li>YYYY-MM-DDThh:mm:ssTZD
49 * <li>YYYY-MM-DDThh:mm:ss.sTZD
50 * </ul>
51 *
52 * Data fields:
53 * <ul>
54 * <li>YYYY = four-digit year
55 * <li>MM = two-digit month (01=January, etc.)
56 * <li>DD = two-digit day of month (01 through 31)
57 * <li>hh = two digits of hour (00 through 23)
58 * <li>mm = two digits of minute (00 through 59)
59 * <li>ss = two digits of second (00 through 59)
60 * <li>s = one or more digits representing a decimal fraction of a second
61 * <li>TZD = time zone designator (Z or +hh:mm or -hh:mm)
62 * </ul>
63 *
64 * Note that ISO 8601 does not seem to allow years less than 1000 or greater
65 * than 9999. We allow any year, even negative ones. The year is formatted
66 * as "%.4d".
67 * <p>
68 * <em>Note:</em> Tolerate missing TZD, assume is UTC. Photoshop 8 writes
69 * dates like this for exif:GPSTimeStamp.<br>
70 * <em>Note:</em> DOES NOT APPLY ANYMORE.
71 * Tolerate missing date portion, in case someone foolishly
72 * writes a time-only value that way.
73 *
74 * @param iso8601String a date string that is ISO 8601 conform.
75 * @return Returns a <code>Calendar</code>.
76 * @throws XMPException Is thrown when the string is non-conform.
77 */
78 public static XMPDateTime parse(String iso8601String) throws XMPException
79 {
80 return parse(iso8601String, new XMPDateTimeImpl());
81 }
82
83
84 /**
85 * @param iso8601String a date string that is ISO 8601 conform.
86 * @param binValue an existing XMPDateTime to set with the parsed date
87 * @return Returns an XMPDateTime-object containing the ISO8601-date.
88 * @throws XMPException Is thrown when the string is non-conform.
89 */
90 public static XMPDateTime parse(String iso8601String, XMPDateTime binValue) throws XMPException
91 {
92 if (iso8601String == null)
93 {
94 throw new XMPException("Parameter must not be null", XMPError.BADPARAM);
95 }
96 else if (iso8601String.length() == 0)
97 {
98 return binValue;
99 }
100
101 ParseState input = new ParseState(iso8601String);
102 int value;
103
104 if (input.ch(0) == '-')
105 {
106 input.skip();
107 }
108
109 // Extract the year.
110 value = input.gatherInt("Invalid year in date string", 9999);
111 if (input.hasNext() && input.ch() != '-')
112 {
113 throw new XMPException("Invalid date string, after year", XMPError.BADVALUE);
114 }
115
116 if (input.ch(0) == '-')
117 {
118 value = -value;
119 }
120 binValue.setYear(value);
121 if (!input.hasNext())
122 {
123 return binValue;
124 }
125 input.skip();
126
127
128 // Extract the month.
129 value = input.gatherInt("Invalid month in date string", 12);
130 if (input.hasNext() && input.ch() != '-')
131 {
132 throw new XMPException("Invalid date string, after month", XMPError.BADVALUE);
133 }
134 binValue.setMonth(value);
135 if (!input.hasNext())
136 {
137 return binValue;
138 }
139 input.skip();
140
141
142 // Extract the day.
143 value = input.gatherInt("Invalid day in date string", 31);
144 if (input.hasNext() && input.ch() != 'T')
145 {
146 throw new XMPException("Invalid date string, after day", XMPError.BADVALUE);
147 }
148 binValue.setDay(value);
149 if (!input.hasNext())
150 {
151 return binValue;
152 }
153 input.skip();
154
155 // Extract the hour.
156 value = input.gatherInt("Invalid hour in date string", 23);
157 binValue.setHour(value);
158 if (!input.hasNext())
159 {
160 return binValue;
161 }
162
163 // Extract the minute.
164 if (input.ch() == ':')
165 {
166 input.skip();
167 value = input.gatherInt("Invalid minute in date string", 59);
168 if (input.hasNext() &&
169 input.ch() != ':' && input.ch() != 'Z' && input.ch() != '+' && input.ch() != '-')
170 {
171 throw new XMPException("Invalid date string, after minute", XMPError.BADVALUE);
172 }
173 binValue.setMinute(value);
174 }
175
176 if (!input.hasNext())
177 {
178 return binValue;
179 }
180 else if (input.hasNext() && input.ch() == ':')
181 {
182 input.skip();
183 value = input.gatherInt("Invalid whole seconds in date string", 59);
184 if (input.hasNext() && input.ch() != '.' && input.ch() != 'Z' &&
185 input.ch() != '+' && input.ch() != '-')
186 {
187 throw new XMPException("Invalid date string, after whole seconds",
188 XMPError.BADVALUE);
189 }
190 binValue.setSecond(value);
191 if (input.ch() == '.')
192 {
193 input.skip();
194 int digits = input.pos();
195 value = input.gatherInt("Invalid fractional seconds in date string", 999999999);
196 if (input.hasNext() &&
197 (input.ch() != 'Z' && input.ch() != '+' && input.ch() != '-'))
198 {
199 throw new XMPException("Invalid date string, after fractional second",
200 XMPError.BADVALUE);
201 }
202 digits = input.pos() - digits;
203 for (; digits > 9; --digits)
204 {
205 value = value / 10;
206 }
207 for (; digits < 9; ++digits)
208 {
209 value = value * 10;
210 }
211 binValue.setNanoSecond(value);
212 }
213 }
214 else if (input.ch() != 'Z' && input.ch() != '+' && input.ch() != '-')
215 {
216 throw new XMPException("Invalid date string, after time", XMPError.BADVALUE);
217 }
218
219
220 int tzSign = 0;
221 int tzHour = 0;
222 int tzMinute = 0;
223
224 if (!input.hasNext())
225 {
226 // no Timezone at all
227 return binValue;
228 }
229 else if (input.ch() == 'Z')
230 {
231 input.skip();
232 }
233 else if (input.hasNext())
234 {
235 if (input.ch() == '+')
236 {
237 tzSign = 1;
238 }
239 else if (input.ch() == '-')
240 {
241 tzSign = -1;
242 }
243 else
244 {
245 throw new XMPException("Time zone must begin with 'Z', '+', or '-'",
246 XMPError.BADVALUE);
247 }
248
249 input.skip();
250 // Extract the time zone hour.
251 tzHour = input.gatherInt("Invalid time zone hour in date string", 23);
252 if (input.hasNext())
253 {
254 if (input.ch() == ':')
255 {
256 input.skip();
257
258 // Extract the time zone minute.
259 tzMinute = input.gatherInt("Invalid time zone minute in date string", 59);
260 }
261 else
262 {
263 throw new XMPException("Invalid date string, after time zone hour",
264 XMPError.BADVALUE);
265 }
266 }
267 }
268
269 // create a corresponding TZ and set it time zone
270 // FfF: would it be better to map into existing time zones?
271 int offset = (tzHour * 3600 * 1000 + tzMinute * 60 * 1000) * tzSign;
272 binValue.setTimeZone(new SimpleTimeZone(offset, ""));
273
274 if (input.hasNext())
275 {
276 throw new XMPException(
277 "Invalid date string, extra chars at end", XMPError.BADVALUE);
278 }
279
280 return binValue;
281 }
282
283
284 /**
285 * Converts a <code>Calendar</code> into an ISO 8601 string.
286 * Format a date according to ISO 8601 and http://www.w3.org/TR/NOTE-datetime:
287 * <ul>
288 * <li>YYYY
289 * <li>YYYY-MM
290 * <li>YYYY-MM-DD
291 * <li>YYYY-MM-DDThh:mmTZD
292 * <li>YYYY-MM-DDThh:mm:ssTZD
293 * <li>YYYY-MM-DDThh:mm:ss.sTZD
294 * </ul>
295 *
296 * Data fields:
297 * <ul>
298 * <li>YYYY = four-digit year
299 * <li>MM = two-digit month (01=January, etc.)
300 * <li>DD = two-digit day of month (01 through 31)
301 * <li>hh = two digits of hour (00 through 23)
302 * <li>mm = two digits of minute (00 through 59)
303 * <li>ss = two digits of second (00 through 59)
304 * <li>s = one or more digits representing a decimal fraction of a second
305 * <li>TZD = time zone designator (Z or +hh:mm or -hh:mm)
306 * </ul>
307 * <p>
308 * <em>Note:</em> ISO 8601 does not seem to allow years less than 1000 or greater than 9999.
309 * We allow any year, even negative ones. The year is formatted as "%.4d".<p>
310 * <em>Note:</em> Fix for bug 1269463 (silently fix out of range values) included in parsing.
311 * The quasi-bogus "time only" values from Photoshop CS are not supported.
312 *
313 * @param dateTime an XMPDateTime-object.
314 * @return Returns an ISO 8601 string.
315 */
316 public static String render(XMPDateTime dateTime)
317 {
318 StringBuffer buffer = new StringBuffer();
319
320 if (dateTime.hasDate())
321 {
322 // year is rendered in any case, even 0000
323 DecimalFormat df = new DecimalFormat("0000", new DecimalFormatSymbols(Locale.ENGLISH));
324 buffer.append(df.format(dateTime.getYear()));
325 if (dateTime.getMonth() == 0)
326 {
327 return buffer.toString();
328 }
329
330 // month
331 df.applyPattern("'-'00");
332 buffer.append(df.format(dateTime.getMonth()));
333 if (dateTime.getDay() == 0)
334 {
335 return buffer.toString();
336 }
337
338 // day
339 buffer.append(df.format(dateTime.getDay()));
340
341 // time, rendered if any time field is not zero
342 if (dateTime.hasTime())
343 {
344 // hours and minutes
345 buffer.append('T');
346 df.applyPattern("00");
347 buffer.append(df.format(dateTime.getHour()));
348 buffer.append(':');
349 buffer.append(df.format(dateTime.getMinute()));
350
351 // seconds and nanoseconds
352 if (dateTime.getSecond() != 0 || dateTime.getNanoSecond() != 0)
353 {
354 double seconds = dateTime.getSecond() + dateTime.getNanoSecond() / 1e9d;
355
356 df.applyPattern(":00.#########");
357 buffer.append(df.format(seconds));
358 }
359
360 // time zone
361 if (dateTime.hasTimeZone())
362 {
363 // used to calculate the time zone offset incl. Daylight Savings
364 long timeInMillis = dateTime.getCalendar().getTimeInMillis();
365 int offset = dateTime.getTimeZone().getOffset(timeInMillis);
366 if (offset == 0)
367 {
368 // UTC
369 buffer.append('Z');
370 }
371 else
372 {
373 int thours = offset / 3600000;
374 int tminutes = Math.abs(offset % 3600000 / 60000);
375 df.applyPattern("+00;-00");
376 buffer.append(df.format(thours));
377 df.applyPattern(":00");
378 buffer.append(df.format(tminutes));
379 }
380 }
381 }
382 }
383 return buffer.toString();
384 }
385
386
387 }
388
389
390 /**
391 * @author Stefan Makswit
392 * @version $Revision$
393 * @since 22.08.2006
394 */
395 class ParseState
396 {
397 /** */
398 private String str;
399 /** */
400 private int pos = 0;
401
402
403 /**
404 * @param str initializes the parser container
405 */
406 public ParseState(String str)
407 {
408 this.str = str;
409 }
410
411
412 /**
413 * @return Returns the length of the input.
414 */
415 public int length()
416 {
417 return str.length();
418 }
419
420
421 /**
422 * @return Returns whether there are more chars to come.
423 */
424 public boolean hasNext()
425 {
426 return pos < str.length();
427 }
428
429
430 /**
431 * @param index index of char
432 * @return Returns char at a certain index.
433 */
434 public char ch(int index)
435 {
436 return index < str.length() ?
437 str.charAt(index) :
438 0x0000;
439 }
440
441
442 /**
443 * @return Returns the current char or 0x0000 if there are no more chars.
444 */
445 public char ch()
446 {
447 return pos < str.length() ?
448 str.charAt(pos) :
449 0x0000;
450 }
451
452
453 /**
454 * Skips the next char.
455 */
456 public void skip()
457 {
458 pos++;
459 }
460
461
462 /**
463 * @return Returns the current position.
464 */
465 public int pos()
466 {
467 return pos;
468 }
469
470
471 /**
472 * Parses a integer from the source and sets the pointer after it.
473 * @param errorMsg Error message to put in the exception if no number can be found
474 * @param maxValue the max value of the number to return
475 * @return Returns the parsed integer.
476 * @throws XMPException Thrown if no integer can be found.
477 */
478 public int gatherInt(String errorMsg, int maxValue) throws XMPException
479 {
480 int value = 0;
481 boolean success = false;
482 char ch = ch(pos);
483 while ('0' <= ch && ch <= '9')
484 {
485 value = (value * 10) + (ch - '0');
486 success = true;
487 pos++;
488 ch = ch(pos);
489 }
490
491 if (success)
492 {
493 if (value > maxValue)
494 {
495 return maxValue;
496 }
497 else if (value < 0)
498 {
499 return 0;
500 }
501 else
502 {
503 return value;
504 }
505 }
506 else
507 {
508 throw new XMPException(errorMsg, XMPError.BADVALUE);
509 }
510 }
511 }
512
513