001/*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package org.apache.commons.lang3.time;
018
019import java.io.IOException;
020import java.io.ObjectInputStream;
021import java.io.Serializable;
022import java.text.DateFormat;
023import java.text.DateFormatSymbols;
024import java.text.FieldPosition;
025import java.util.ArrayList;
026import java.util.Calendar;
027import java.util.Date;
028import java.util.List;
029import java.util.Locale;
030import java.util.TimeZone;
031import java.util.concurrent.ConcurrentHashMap;
032import java.util.concurrent.ConcurrentMap;
033
034import org.apache.commons.lang3.exception.ExceptionUtils;
035
036/**
037 * <p>FastDatePrinter is a fast and thread-safe version of
038 * {@link java.text.SimpleDateFormat}.</p>
039 *
040 * <p>To obtain a FastDatePrinter, use {@link FastDateFormat#getInstance(String, TimeZone, Locale)} 
041 * or another variation of the factory methods of {@link FastDateFormat}.</p>
042 * 
043 * <p>Since FastDatePrinter is thread safe, you can use a static member instance:</p>
044 * <code>
045 *     private static final DatePrinter DATE_PRINTER = FastDateFormat.getInstance("yyyy-MM-dd");
046 * </code>
047 * 
048 * <p>This class can be used as a direct replacement to
049 * {@code SimpleDateFormat} in most formatting situations.
050 * This class is especially useful in multi-threaded server environments.
051 * {@code SimpleDateFormat} is not thread-safe in any JDK version,
052 * nor will it be as Sun have closed the bug/RFE.
053 * </p>
054 *
055 * <p>Only formatting is supported by this class, but all patterns are compatible with
056 * SimpleDateFormat (except time zones and some year patterns - see below).</p>
057 *
058 * <p>Java 1.4 introduced a new pattern letter, {@code 'Z'}, to represent
059 * time zones in RFC822 format (eg. {@code +0800} or {@code -1100}).
060 * This pattern letter can be used here (on all JDK versions).</p>
061 *
062 * <p>In addition, the pattern {@code 'ZZ'} has been made to represent
063 * ISO 8601 extended format time zones (eg. {@code +08:00} or {@code -11:00}).
064 * This introduces a minor incompatibility with Java 1.4, but at a gain of
065 * useful functionality.</p>
066 * 
067 * <p>Starting with JDK7, ISO 8601 support was added using the pattern {@code 'X'}.
068 * To maintain compatibility, {@code 'ZZ'} will continue to be supported, but using
069 * one of the {@code 'X'} formats is recommended.
070 *
071 * <p>Javadoc cites for the year pattern: <i>For formatting, if the number of
072 * pattern letters is 2, the year is truncated to 2 digits; otherwise it is
073 * interpreted as a number.</i> Starting with Java 1.7 a pattern of 'Y' or
074 * 'YYY' will be formatted as '2003', while it was '03' in former Java
075 * versions. FastDatePrinter implements the behavior of Java 7.</p>
076 *
077 * @since 3.2
078 * @see FastDateParser
079 */
080public class FastDatePrinter implements DatePrinter, Serializable {
081    // A lot of the speed in this class comes from caching, but some comes
082    // from the special int to StringBuffer conversion.
083    //
084    // The following produces a padded 2 digit number:
085    //   buffer.append((char)(value / 10 + '0'));
086    //   buffer.append((char)(value % 10 + '0'));
087    //
088    // Note that the fastest append to StringBuffer is a single char (used here).
089    // Note that Integer.toString() is not called, the conversion is simply
090    // taking the value and adding (mathematically) the ASCII value for '0'.
091    // So, don't change this code! It works and is very fast.
092
093    /**
094     * Required for serialization support.
095     *
096     * @see java.io.Serializable
097     */
098    private static final long serialVersionUID = 1L;
099
100    /**
101     * FULL locale dependent date or time style.
102     */
103    public static final int FULL = DateFormat.FULL;
104    /**
105     * LONG locale dependent date or time style.
106     */
107    public static final int LONG = DateFormat.LONG;
108    /**
109     * MEDIUM locale dependent date or time style.
110     */
111    public static final int MEDIUM = DateFormat.MEDIUM;
112    /**
113     * SHORT locale dependent date or time style.
114     */
115    public static final int SHORT = DateFormat.SHORT;
116
117    /**
118     * The pattern.
119     */
120    private final String mPattern;
121    /**
122     * The time zone.
123     */
124    private final TimeZone mTimeZone;
125    /**
126     * The locale.
127     */
128    private final Locale mLocale;
129    /**
130     * The parsed rules.
131     */
132    private transient Rule[] mRules;
133    /**
134     * The estimated maximum length.
135     */
136    private transient int mMaxLengthEstimate;
137
138    // Constructor
139    //-----------------------------------------------------------------------
140    /**
141     * <p>Constructs a new FastDatePrinter.</p>
142     * Use {@link FastDateFormat#getInstance(String, TimeZone, Locale)}  or another variation of the 
143     * factory methods of {@link FastDateFormat} to get a cached FastDatePrinter instance.
144     *
145     * @param pattern  {@link java.text.SimpleDateFormat} compatible pattern
146     * @param timeZone  non-null time zone to use
147     * @param locale  non-null locale to use
148     * @throws NullPointerException if pattern, timeZone, or locale is null.
149     */
150    protected FastDatePrinter(final String pattern, final TimeZone timeZone, final Locale locale) {
151        mPattern = pattern;
152        mTimeZone = timeZone;
153        mLocale = locale;
154
155        init();
156    }
157
158    /**
159     * <p>Initializes the instance for first use.</p>
160     */
161    private void init() {
162        final List<Rule> rulesList = parsePattern();
163        mRules = rulesList.toArray(new Rule[rulesList.size()]);
164
165        int len = 0;
166        for (int i=mRules.length; --i >= 0; ) {
167            len += mRules[i].estimateLength();
168        }
169
170        mMaxLengthEstimate = len;
171    }
172
173    // Parse the pattern
174    //-----------------------------------------------------------------------
175    /**
176     * <p>Returns a list of Rules given a pattern.</p>
177     *
178     * @return a {@code List} of Rule objects
179     * @throws IllegalArgumentException if pattern is invalid
180     */
181    protected List<Rule> parsePattern() {
182        final DateFormatSymbols symbols = new DateFormatSymbols(mLocale);
183        final List<Rule> rules = new ArrayList<Rule>();
184
185        final String[] ERAs = symbols.getEras();
186        final String[] months = symbols.getMonths();
187        final String[] shortMonths = symbols.getShortMonths();
188        final String[] weekdays = symbols.getWeekdays();
189        final String[] shortWeekdays = symbols.getShortWeekdays();
190        final String[] AmPmStrings = symbols.getAmPmStrings();
191
192        final int length = mPattern.length();
193        final int[] indexRef = new int[1];
194
195        for (int i = 0; i < length; i++) {
196            indexRef[0] = i;
197            final String token = parseToken(mPattern, indexRef);
198            i = indexRef[0];
199
200            final int tokenLen = token.length();
201            if (tokenLen == 0) {
202                break;
203            }
204
205            Rule rule;
206            final char c = token.charAt(0);
207
208            switch (c) {
209            case 'G': // era designator (text)
210                rule = new TextField(Calendar.ERA, ERAs);
211                break;
212            case 'y': // year (number)
213            case 'Y': // week year
214                if (tokenLen == 2) {
215                    rule = TwoDigitYearField.INSTANCE;
216                } else {
217                    rule = selectNumberRule(Calendar.YEAR, tokenLen < 4 ? 4 : tokenLen);
218                }
219                if (c == 'Y') {
220                    rule = new WeekYear((NumberRule) rule);
221                }
222                break;
223            case 'M': // month in year (text and number)
224                if (tokenLen >= 4) {
225                    rule = new TextField(Calendar.MONTH, months);
226                } else if (tokenLen == 3) {
227                    rule = new TextField(Calendar.MONTH, shortMonths);
228                } else if (tokenLen == 2) {
229                    rule = TwoDigitMonthField.INSTANCE;
230                } else {
231                    rule = UnpaddedMonthField.INSTANCE;
232                }
233                break;
234            case 'd': // day in month (number)
235                rule = selectNumberRule(Calendar.DAY_OF_MONTH, tokenLen);
236                break;
237            case 'h': // hour in am/pm (number, 1..12)
238                rule = new TwelveHourField(selectNumberRule(Calendar.HOUR, tokenLen));
239                break;
240            case 'H': // hour in day (number, 0..23)
241                rule = selectNumberRule(Calendar.HOUR_OF_DAY, tokenLen);
242                break;
243            case 'm': // minute in hour (number)
244                rule = selectNumberRule(Calendar.MINUTE, tokenLen);
245                break;
246            case 's': // second in minute (number)
247                rule = selectNumberRule(Calendar.SECOND, tokenLen);
248                break;
249            case 'S': // millisecond (number)
250                rule = selectNumberRule(Calendar.MILLISECOND, tokenLen);
251                break;
252            case 'E': // day in week (text)
253                rule = new TextField(Calendar.DAY_OF_WEEK, tokenLen < 4 ? shortWeekdays : weekdays);
254                break;
255            case 'u': // day in week (number)
256                rule = new DayInWeekField(selectNumberRule(Calendar.DAY_OF_WEEK, tokenLen));
257                break;
258            case 'D': // day in year (number)
259                rule = selectNumberRule(Calendar.DAY_OF_YEAR, tokenLen);
260                break;
261            case 'F': // day of week in month (number)
262                rule = selectNumberRule(Calendar.DAY_OF_WEEK_IN_MONTH, tokenLen);
263                break;
264            case 'w': // week in year (number)
265                rule = selectNumberRule(Calendar.WEEK_OF_YEAR, tokenLen);
266                break;
267            case 'W': // week in month (number)
268                rule = selectNumberRule(Calendar.WEEK_OF_MONTH, tokenLen);
269                break;
270            case 'a': // am/pm marker (text)
271                rule = new TextField(Calendar.AM_PM, AmPmStrings);
272                break;
273            case 'k': // hour in day (1..24)
274                rule = new TwentyFourHourField(selectNumberRule(Calendar.HOUR_OF_DAY, tokenLen));
275                break;
276            case 'K': // hour in am/pm (0..11)
277                rule = selectNumberRule(Calendar.HOUR, tokenLen);
278                break;
279            case 'X': // ISO 8601 
280                rule = Iso8601_Rule.getRule(tokenLen);
281                break;    
282            case 'z': // time zone (text)
283                if (tokenLen >= 4) {
284                    rule = new TimeZoneNameRule(mTimeZone, mLocale, TimeZone.LONG);
285                } else {
286                    rule = new TimeZoneNameRule(mTimeZone, mLocale, TimeZone.SHORT);
287                }
288                break;
289            case 'Z': // time zone (value)
290                if (tokenLen == 1) {
291                    rule = TimeZoneNumberRule.INSTANCE_NO_COLON;
292                } else if (tokenLen == 2) {
293                    rule = Iso8601_Rule.ISO8601_HOURS_COLON_MINUTES;
294                } else {
295                    rule = TimeZoneNumberRule.INSTANCE_COLON;
296                }
297                break;
298            case '\'': // literal text
299                final String sub = token.substring(1);
300                if (sub.length() == 1) {
301                    rule = new CharacterLiteral(sub.charAt(0));
302                } else {
303                    rule = new StringLiteral(sub);
304                }
305                break;
306            default:
307                throw new IllegalArgumentException("Illegal pattern component: " + token);
308            }
309
310            rules.add(rule);
311        }
312
313        return rules;
314    }
315
316    /**
317     * <p>Performs the parsing of tokens.</p>
318     *
319     * @param pattern  the pattern
320     * @param indexRef  index references
321     * @return parsed token
322     */
323    protected String parseToken(final String pattern, final int[] indexRef) {
324        final StringBuilder buf = new StringBuilder();
325
326        int i = indexRef[0];
327        final int length = pattern.length();
328
329        char c = pattern.charAt(i);
330        if (c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z') {
331            // Scan a run of the same character, which indicates a time
332            // pattern.
333            buf.append(c);
334
335            while (i + 1 < length) {
336                final char peek = pattern.charAt(i + 1);
337                if (peek == c) {
338                    buf.append(c);
339                    i++;
340                } else {
341                    break;
342                }
343            }
344        } else {
345            // This will identify token as text.
346            buf.append('\'');
347
348            boolean inLiteral = false;
349
350            for (; i < length; i++) {
351                c = pattern.charAt(i);
352
353                if (c == '\'') {
354                    if (i + 1 < length && pattern.charAt(i + 1) == '\'') {
355                        // '' is treated as escaped '
356                        i++;
357                        buf.append(c);
358                    } else {
359                        inLiteral = !inLiteral;
360                    }
361                } else if (!inLiteral &&
362                         (c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z')) {
363                    i--;
364                    break;
365                } else {
366                    buf.append(c);
367                }
368            }
369        }
370
371        indexRef[0] = i;
372        return buf.toString();
373    }
374
375    /**
376     * <p>Gets an appropriate rule for the padding required.</p>
377     *
378     * @param field  the field to get a rule for
379     * @param padding  the padding required
380     * @return a new rule with the correct padding
381     */
382    protected NumberRule selectNumberRule(final int field, final int padding) {
383        switch (padding) {
384        case 1:
385            return new UnpaddedNumberField(field);
386        case 2:
387            return new TwoDigitNumberField(field);
388        default:
389            return new PaddedNumberField(field, padding);
390        }
391    }
392
393    // Format methods
394    //-----------------------------------------------------------------------
395    /**
396     * <p>Formats a {@code Date}, {@code Calendar} or
397     * {@code Long} (milliseconds) object.</p>
398     * @deprecated Use {{@link #format(Date)}, {{@link #format(Calendar)}, {{@link #format(long)}, or {{@link #format(Object)}
399     * @param obj  the object to format
400     * @param toAppendTo  the buffer to append to
401     * @param pos  the position - ignored
402     * @return the buffer passed in
403     */
404    @Deprecated
405    @Override
406    public StringBuffer format(final Object obj, final StringBuffer toAppendTo, final FieldPosition pos) {
407        if (obj instanceof Date) {
408            return format((Date) obj, toAppendTo);
409        } else if (obj instanceof Calendar) {
410            return format((Calendar) obj, toAppendTo);
411        } else if (obj instanceof Long) {
412            return format(((Long) obj).longValue(), toAppendTo);
413        } else {
414            throw new IllegalArgumentException("Unknown class: " +
415                (obj == null ? "<null>" : obj.getClass().getName()));
416        }
417    }
418
419    /**
420     * <p>Formats a {@code Date}, {@code Calendar} or
421     * {@code Long} (milliseconds) object.</p>
422     * @since 3.5
423     * @param obj  the object to format
424     * @return The formatted value.
425     */
426    String format(Object obj) {
427        if (obj instanceof Date) {
428            return format((Date) obj);
429        } else if (obj instanceof Calendar) {
430            return format((Calendar) obj);
431        } else if (obj instanceof Long) {
432            return format(((Long) obj).longValue());
433        } else {
434            throw new IllegalArgumentException("Unknown class: " +
435                (obj == null ? "<null>" : obj.getClass().getName()));
436        }
437    }
438
439    /* (non-Javadoc)
440     * @see org.apache.commons.lang3.time.DatePrinter#format(long)
441     */
442    @Override
443    public String format(final long millis) {
444        final Calendar c = newCalendar();
445        c.setTimeInMillis(millis);
446        return applyRulesToString(c);
447    }
448
449    /**
450     * Creates a String representation of the given Calendar by applying the rules of this printer to it.
451     * @param c the Calender to apply the rules to.
452     * @return a String representation of the given Calendar.
453     */
454    private String applyRulesToString(final Calendar c) {
455        return applyRules(c, new StringBuilder(mMaxLengthEstimate)).toString();
456    }
457
458    /**
459     * Creation method for new calender instances.
460     * @return a new Calendar instance.
461     */
462    private Calendar newCalendar() {
463        return Calendar.getInstance(mTimeZone, mLocale);
464    }
465
466    /* (non-Javadoc)
467     * @see org.apache.commons.lang3.time.DatePrinter#format(java.util.Date)
468     */
469    @Override
470    public String format(final Date date) {
471        final Calendar c = newCalendar();
472        c.setTime(date);
473        return applyRulesToString(c);
474    }
475
476    /* (non-Javadoc)
477     * @see org.apache.commons.lang3.time.DatePrinter#format(java.util.Calendar)
478     */
479    @Override
480    public String format(final Calendar calendar) {
481        return format(calendar, new StringBuilder(mMaxLengthEstimate)).toString();
482    }
483
484    /* (non-Javadoc)
485     * @see org.apache.commons.lang3.time.DatePrinter#format(long, java.lang.StringBuffer)
486     */
487    @Override
488    public StringBuffer format(final long millis, final StringBuffer buf) {
489        final Calendar c = newCalendar();
490        c.setTimeInMillis(millis);
491        return (StringBuffer) applyRules(c, (Appendable)buf);
492    }
493
494    /* (non-Javadoc)
495     * @see org.apache.commons.lang3.time.DatePrinter#format(java.util.Date, java.lang.StringBuffer)
496     */
497    @Override
498    public StringBuffer format(final Date date, final StringBuffer buf) {
499        final Calendar c = newCalendar();
500        c.setTime(date);
501        return (StringBuffer) applyRules(c, (Appendable)buf);
502    }
503
504    /* (non-Javadoc)
505     * @see org.apache.commons.lang3.time.DatePrinter#format(java.util.Calendar, java.lang.StringBuffer)
506     */
507    @Override
508    public StringBuffer format(final Calendar calendar, final StringBuffer buf) {
509        // do not pass in calendar directly, this will cause TimeZone of FastDatePrinter to be ignored
510        return format(calendar.getTime(), buf);
511    }
512
513    /* (non-Javadoc)
514     * @see org.apache.commons.lang3.time.DatePrinter#format(long, java.lang.Appendable)
515     */
516    @Override
517    public <B extends Appendable> B format(final long millis, final B buf) {
518        final Calendar c = newCalendar();
519        c.setTimeInMillis(millis);
520        return applyRules(c, buf);
521    }
522
523    /* (non-Javadoc)
524     * @see org.apache.commons.lang3.time.DatePrinter#format(java.util.Date, java.lang.Appendable)
525     */
526    @Override
527    public <B extends Appendable> B format(final Date date, final B buf) {
528        final Calendar c = newCalendar();
529        c.setTime(date);
530        return applyRules(c, buf);
531    }
532
533    /* (non-Javadoc)
534     * @see org.apache.commons.lang3.time.DatePrinter#format(java.util.Calendar, java.lang.Appendable)
535     */
536    @Override
537    public <B extends Appendable> B format(Calendar calendar, final B buf) {
538        // do not pass in calendar directly, this will cause TimeZone of FastDatePrinter to be ignored
539        if(!calendar.getTimeZone().equals(mTimeZone)) {
540            calendar = (Calendar)calendar.clone();
541            calendar.setTimeZone(mTimeZone);
542        }
543        return applyRules(calendar, buf);
544    }
545
546    /**
547     * @deprecated use {@link #format(Calendar)} or {@link #format(Calendar, Appendable)}
548     */
549    @Deprecated
550    protected StringBuffer applyRules(final Calendar calendar, final StringBuffer buf) {
551        return (StringBuffer) applyRules(calendar, (Appendable)buf);
552    }
553
554    /**
555     * <p>Performs the formatting by applying the rules to the
556     * specified calendar.</p>
557     *
558     * @param calendar  the calendar to format
559     * @param buf  the buffer to format into
560     * @param <B> the Appendable class type, usually StringBuilder or StringBuffer.
561     * @return the specified string buffer
562     */
563    private <B extends Appendable> B applyRules(final Calendar calendar, final B buf) {
564        try {
565            for (final Rule rule : mRules) {
566                rule.appendTo(buf, calendar);
567            }
568        } catch (IOException ioe) {
569            ExceptionUtils.rethrow(ioe);
570        }
571        return buf;
572    }
573
574    // Accessors
575    //-----------------------------------------------------------------------
576    /* (non-Javadoc)
577     * @see org.apache.commons.lang3.time.DatePrinter#getPattern()
578     */
579    @Override
580    public String getPattern() {
581        return mPattern;
582    }
583
584    /* (non-Javadoc)
585     * @see org.apache.commons.lang3.time.DatePrinter#getTimeZone()
586     */
587    @Override
588    public TimeZone getTimeZone() {
589        return mTimeZone;
590    }
591
592    /* (non-Javadoc)
593     * @see org.apache.commons.lang3.time.DatePrinter#getLocale()
594     */
595    @Override
596    public Locale getLocale() {
597        return mLocale;
598    }
599
600    /**
601     * <p>Gets an estimate for the maximum string length that the
602     * formatter will produce.</p>
603     *
604     * <p>The actual formatted length will almost always be less than or
605     * equal to this amount.</p>
606     *
607     * @return the maximum formatted length
608     */
609    public int getMaxLengthEstimate() {
610        return mMaxLengthEstimate;
611    }
612
613    // Basics
614    //-----------------------------------------------------------------------
615    /**
616     * <p>Compares two objects for equality.</p>
617     *
618     * @param obj  the object to compare to
619     * @return {@code true} if equal
620     */
621    @Override
622    public boolean equals(final Object obj) {
623        if (obj instanceof FastDatePrinter == false) {
624            return false;
625        }
626        final FastDatePrinter other = (FastDatePrinter) obj;
627        return mPattern.equals(other.mPattern)
628            && mTimeZone.equals(other.mTimeZone) 
629            && mLocale.equals(other.mLocale);
630    }
631
632    /**
633     * <p>Returns a hashcode compatible with equals.</p>
634     *
635     * @return a hashcode compatible with equals
636     */
637    @Override
638    public int hashCode() {
639        return mPattern.hashCode() + 13 * (mTimeZone.hashCode() + 13 * mLocale.hashCode());
640    }
641
642    /**
643     * <p>Gets a debugging string version of this formatter.</p>
644     *
645     * @return a debugging string
646     */
647    @Override
648    public String toString() {
649        return "FastDatePrinter[" + mPattern + "," + mLocale + "," + mTimeZone.getID() + "]";
650    }
651
652    // Serializing
653    //-----------------------------------------------------------------------
654    /**
655     * Create the object after serialization. This implementation reinitializes the
656     * transient properties.
657     *
658     * @param in ObjectInputStream from which the object is being deserialized.
659     * @throws IOException if there is an IO issue.
660     * @throws ClassNotFoundException if a class cannot be found.
661     */
662    private void readObject(final ObjectInputStream in) throws IOException, ClassNotFoundException {
663        in.defaultReadObject();
664        init();
665    }
666
667    /**
668     * Appends two digits to the given buffer.
669     *
670     * @param buffer the buffer to append to.
671     * @param value the value to append digits from.
672     */
673    private static void appendDigits(final Appendable buffer, final int value) throws IOException {
674        buffer.append((char)(value / 10 + '0'));
675        buffer.append((char)(value % 10 + '0'));
676    }
677
678    private static final int MAX_DIGITS = 10; // log10(Integer.MAX_VALUE) ~= 9.3
679
680    /**
681     * Appends all digits to the given buffer.
682     *
683     * @param buffer the buffer to append to.
684     * @param value the value to append digits from.
685     */
686    private static void appendFullDigits(final Appendable buffer, int value, int minFieldWidth) throws IOException {
687        // specialized paths for 1 to 4 digits -> avoid the memory allocation from the temporary work array
688        // see LANG-1248
689        if (value < 10000) {
690            // less memory allocation path works for four digits or less
691
692            int nDigits = 4;
693            if (value < 1000) {
694                --nDigits;
695                if (value < 100) {
696                    --nDigits;
697                    if (value < 10) {
698                        --nDigits;
699                    }
700                }
701            }
702            // left zero pad
703            for (int i = minFieldWidth - nDigits; i > 0; --i) {
704                buffer.append('0');
705            }
706
707            switch (nDigits) {
708            case 4:
709                buffer.append((char) (value / 1000 + '0'));
710                value %= 1000;
711            case 3:
712                if (value >= 100) {
713                    buffer.append((char) (value / 100 + '0'));
714                    value %= 100;
715                } else {
716                    buffer.append('0');
717                }
718            case 2:
719                if (value >= 10) {
720                    buffer.append((char) (value / 10 + '0'));
721                    value %= 10;
722                } else {
723                    buffer.append('0');
724                }
725            case 1:
726                buffer.append((char) (value + '0'));
727            }
728        } else {
729            // more memory allocation path works for any digits
730
731            // build up decimal representation in reverse
732            char[] work = new char[MAX_DIGITS];
733            int digit = 0;
734            while (value != 0) {
735                work[digit++] = (char) (value % 10 + '0');
736                value = value / 10;
737            }
738
739            // pad with zeros
740            while (digit < minFieldWidth) {
741                buffer.append('0');
742                --minFieldWidth;
743            }
744
745            // reverse
746            while (--digit >= 0) {
747                buffer.append(work[digit]);
748            }
749        }
750    }
751
752    // Rules
753    //-----------------------------------------------------------------------
754    /**
755     * <p>Inner class defining a rule.</p>
756     */
757    private interface Rule {
758        /**
759         * Returns the estimated length of the result.
760         *
761         * @return the estimated length
762         */
763        int estimateLength();
764
765        /**
766         * Appends the value of the specified calendar to the output buffer based on the rule implementation.
767         *
768         * @param buf the output buffer
769         * @param calendar calendar to be appended
770         */
771        void appendTo(Appendable buf, Calendar calendar) throws IOException;
772    }
773
774    /**
775     * <p>Inner class defining a numeric rule.</p>
776     */
777    private interface NumberRule extends Rule {
778        /**
779         * Appends the specified value to the output buffer based on the rule implementation.
780         *
781         * @param buffer the output buffer
782         * @param value the value to be appended
783         */
784        void appendTo(Appendable buffer, int value) throws IOException;
785    }
786
787    /**
788     * <p>Inner class to output a constant single character.</p>
789     */
790    private static class CharacterLiteral implements Rule {
791        private final char mValue;
792
793        /**
794         * Constructs a new instance of {@code CharacterLiteral}
795         * to hold the specified value.
796         *
797         * @param value the character literal
798         */
799        CharacterLiteral(final char value) {
800            mValue = value;
801        }
802
803        /**
804         * {@inheritDoc}
805         */
806        @Override
807        public int estimateLength() {
808            return 1;
809        }
810
811        /**
812         * {@inheritDoc}
813         */
814        @Override
815        public void appendTo(final Appendable buffer, final Calendar calendar) throws IOException {
816            buffer.append(mValue);
817        }
818    }
819
820    /**
821     * <p>Inner class to output a constant string.</p>
822     */
823    private static class StringLiteral implements Rule {
824        private final String mValue;
825
826        /**
827         * Constructs a new instance of {@code StringLiteral}
828         * to hold the specified value.
829         *
830         * @param value the string literal
831         */
832        StringLiteral(final String value) {
833            mValue = value;
834        }
835
836        /**
837         * {@inheritDoc}
838         */
839        @Override
840        public int estimateLength() {
841            return mValue.length();
842        }
843
844        /**
845         * {@inheritDoc}
846         */
847        @Override
848        public void appendTo(final Appendable buffer, final Calendar calendar) throws IOException {
849            buffer.append(mValue);
850        }
851    }
852
853    /**
854     * <p>Inner class to output one of a set of values.</p>
855     */
856    private static class TextField implements Rule {
857        private final int mField;
858        private final String[] mValues;
859
860        /**
861         * Constructs an instance of {@code TextField}
862         * with the specified field and values.
863         *
864         * @param field the field
865         * @param values the field values
866         */
867        TextField(final int field, final String[] values) {
868            mField = field;
869            mValues = values;
870        }
871
872        /**
873         * {@inheritDoc}
874         */
875        @Override
876        public int estimateLength() {
877            int max = 0;
878            for (int i=mValues.length; --i >= 0; ) {
879                final int len = mValues[i].length();
880                if (len > max) {
881                    max = len;
882                }
883            }
884            return max;
885        }
886
887        /**
888         * {@inheritDoc}
889         */
890        @Override
891        public void appendTo(final Appendable buffer, final Calendar calendar) throws IOException {
892            buffer.append(mValues[calendar.get(mField)]);
893        }
894    }
895
896    /**
897     * <p>Inner class to output an unpadded number.</p>
898     */
899    private static class UnpaddedNumberField implements NumberRule {
900        private final int mField;
901
902        /**
903         * Constructs an instance of {@code UnpadedNumberField} with the specified field.
904         *
905         * @param field the field
906         */
907        UnpaddedNumberField(final int field) {
908            mField = field;
909        }
910
911        /**
912         * {@inheritDoc}
913         */
914        @Override
915        public int estimateLength() {
916            return 4;
917        }
918
919        /**
920         * {@inheritDoc}
921         */
922        @Override
923        public void appendTo(final Appendable buffer, final Calendar calendar) throws IOException {
924            appendTo(buffer, calendar.get(mField));
925        }
926
927        /**
928         * {@inheritDoc}
929         */
930        @Override
931        public final void appendTo(final Appendable buffer, final int value) throws IOException {
932            if (value < 10) {
933                buffer.append((char)(value + '0'));
934            } else if (value < 100) {
935                appendDigits(buffer, value);
936            } else {
937               appendFullDigits(buffer, value, 1);
938            }
939        }
940    }
941
942    /**
943     * <p>Inner class to output an unpadded month.</p>
944     */
945    private static class UnpaddedMonthField implements NumberRule {
946        static final UnpaddedMonthField INSTANCE = new UnpaddedMonthField();
947
948        /**
949         * Constructs an instance of {@code UnpaddedMonthField}.
950         *
951         */
952        UnpaddedMonthField() {
953            super();
954        }
955
956        /**
957         * {@inheritDoc}
958         */
959        @Override
960        public int estimateLength() {
961            return 2;
962        }
963
964        /**
965         * {@inheritDoc}
966         */
967        @Override
968        public void appendTo(final Appendable buffer, final Calendar calendar) throws IOException {
969            appendTo(buffer, calendar.get(Calendar.MONTH) + 1);
970        }
971
972        /**
973         * {@inheritDoc}
974         */
975        @Override
976        public final void appendTo(final Appendable buffer, final int value) throws IOException {
977            if (value < 10) {
978                buffer.append((char)(value + '0'));
979            } else {
980                appendDigits(buffer, value);
981            }
982        }
983    }
984
985    /**
986     * <p>Inner class to output a padded number.</p>
987     */
988    private static class PaddedNumberField implements NumberRule {
989        private final int mField;
990        private final int mSize;
991
992        /**
993         * Constructs an instance of {@code PaddedNumberField}.
994         *
995         * @param field the field
996         * @param size size of the output field
997         */
998        PaddedNumberField(final int field, final int size) {
999            if (size < 3) {
1000                // Should use UnpaddedNumberField or TwoDigitNumberField.
1001                throw new IllegalArgumentException();
1002            }
1003            mField = field;
1004            mSize = size;
1005        }
1006
1007        /**
1008         * {@inheritDoc}
1009         */
1010        @Override
1011        public int estimateLength() {
1012            return mSize;
1013        }
1014
1015        /**
1016         * {@inheritDoc}
1017         */
1018        @Override
1019        public void appendTo(final Appendable buffer, final Calendar calendar) throws IOException {
1020            appendTo(buffer, calendar.get(mField));
1021        }
1022
1023        /**
1024         * {@inheritDoc}
1025         */
1026        @Override
1027        public final void appendTo(final Appendable buffer, int value) throws IOException {
1028            appendFullDigits(buffer, value, mSize);
1029        }
1030    }
1031
1032    /**
1033     * <p>Inner class to output a two digit number.</p>
1034     */
1035    private static class TwoDigitNumberField implements NumberRule {
1036        private final int mField;
1037
1038        /**
1039         * Constructs an instance of {@code TwoDigitNumberField} with the specified field.
1040         *
1041         * @param field the field
1042         */
1043        TwoDigitNumberField(final int field) {
1044            mField = field;
1045        }
1046
1047        /**
1048         * {@inheritDoc}
1049         */
1050        @Override
1051        public int estimateLength() {
1052            return 2;
1053        }
1054
1055        /**
1056         * {@inheritDoc}
1057         */
1058        @Override
1059        public void appendTo(final Appendable buffer, final Calendar calendar) throws IOException {
1060            appendTo(buffer, calendar.get(mField));
1061        }
1062
1063        /**
1064         * {@inheritDoc}
1065         */
1066        @Override
1067        public final void appendTo(final Appendable buffer, final int value) throws IOException {
1068            if (value < 100) {
1069                appendDigits(buffer, value);
1070            } else {
1071                appendFullDigits(buffer, value, 2);
1072            }
1073        }
1074    }
1075
1076    /**
1077     * <p>Inner class to output a two digit year.</p>
1078     */
1079    private static class TwoDigitYearField implements NumberRule {
1080        static final TwoDigitYearField INSTANCE = new TwoDigitYearField();
1081
1082        /**
1083         * Constructs an instance of {@code TwoDigitYearField}.
1084         */
1085        TwoDigitYearField() {
1086            super();
1087        }
1088
1089        /**
1090         * {@inheritDoc}
1091         */
1092        @Override
1093        public int estimateLength() {
1094            return 2;
1095        }
1096
1097        /**
1098         * {@inheritDoc}
1099         */
1100        @Override
1101        public void appendTo(final Appendable buffer, final Calendar calendar) throws IOException {
1102            appendTo(buffer, calendar.get(Calendar.YEAR) % 100);
1103        }
1104
1105        /**
1106         * {@inheritDoc}
1107         */
1108        @Override
1109        public final void appendTo(final Appendable buffer, final int value) throws IOException {
1110            appendDigits(buffer, value);
1111        }
1112    }
1113
1114    /**
1115     * <p>Inner class to output a two digit month.</p>
1116     */
1117    private static class TwoDigitMonthField implements NumberRule {
1118        static final TwoDigitMonthField INSTANCE = new TwoDigitMonthField();
1119
1120        /**
1121         * Constructs an instance of {@code TwoDigitMonthField}.
1122         */
1123        TwoDigitMonthField() {
1124            super();
1125        }
1126
1127        /**
1128         * {@inheritDoc}
1129         */
1130        @Override
1131        public int estimateLength() {
1132            return 2;
1133        }
1134
1135        /**
1136         * {@inheritDoc}
1137         */
1138        @Override
1139        public void appendTo(final Appendable buffer, final Calendar calendar) throws IOException {
1140            appendTo(buffer, calendar.get(Calendar.MONTH) + 1);
1141        }
1142
1143        /**
1144         * {@inheritDoc}
1145         */
1146        @Override
1147        public final void appendTo(final Appendable buffer, final int value) throws IOException {
1148            appendDigits(buffer, value);
1149        }
1150    }
1151
1152    /**
1153     * <p>Inner class to output the twelve hour field.</p>
1154     */
1155    private static class TwelveHourField implements NumberRule {
1156        private final NumberRule mRule;
1157
1158        /**
1159         * Constructs an instance of {@code TwelveHourField} with the specified
1160         * {@code NumberRule}.
1161         *
1162         * @param rule the rule
1163         */
1164        TwelveHourField(final NumberRule rule) {
1165            mRule = rule;
1166        }
1167
1168        /**
1169         * {@inheritDoc}
1170         */
1171        @Override
1172        public int estimateLength() {
1173            return mRule.estimateLength();
1174        }
1175
1176        /**
1177         * {@inheritDoc}
1178         */
1179        @Override
1180        public void appendTo(final Appendable buffer, final Calendar calendar) throws IOException {
1181            int value = calendar.get(Calendar.HOUR);
1182            if (value == 0) {
1183                value = calendar.getLeastMaximum(Calendar.HOUR) + 1;
1184            }
1185            mRule.appendTo(buffer, value);
1186        }
1187
1188        /**
1189         * {@inheritDoc}
1190         */
1191        @Override
1192        public void appendTo(final Appendable buffer, final int value) throws IOException {
1193            mRule.appendTo(buffer, value);
1194        }
1195    }
1196
1197    /**
1198     * <p>Inner class to output the twenty four hour field.</p>
1199     */
1200    private static class TwentyFourHourField implements NumberRule {
1201        private final NumberRule mRule;
1202
1203        /**
1204         * Constructs an instance of {@code TwentyFourHourField} with the specified
1205         * {@code NumberRule}.
1206         *
1207         * @param rule the rule
1208         */
1209        TwentyFourHourField(final NumberRule rule) {
1210            mRule = rule;
1211        }
1212
1213        /**
1214         * {@inheritDoc}
1215         */
1216        @Override
1217        public int estimateLength() {
1218            return mRule.estimateLength();
1219        }
1220
1221        /**
1222         * {@inheritDoc}
1223         */
1224        @Override
1225        public void appendTo(final Appendable buffer, final Calendar calendar) throws IOException {
1226            int value = calendar.get(Calendar.HOUR_OF_DAY);
1227            if (value == 0) {
1228                value = calendar.getMaximum(Calendar.HOUR_OF_DAY) + 1;
1229            }
1230            mRule.appendTo(buffer, value);
1231        }
1232
1233        /**
1234         * {@inheritDoc}
1235         */
1236        @Override
1237        public void appendTo(final Appendable buffer, final int value) throws IOException {
1238            mRule.appendTo(buffer, value);
1239        }
1240    }
1241
1242    /**
1243     * <p>Inner class to output the numeric day in week.</p>
1244     */
1245    private static class DayInWeekField implements NumberRule {
1246        private final NumberRule mRule;
1247
1248        DayInWeekField(final NumberRule rule) {
1249            mRule = rule;
1250        }
1251
1252        @Override
1253        public int estimateLength() {
1254            return mRule.estimateLength();
1255        }
1256
1257        @Override
1258        public void appendTo(final Appendable buffer, final Calendar calendar) throws IOException {
1259            int value = calendar.get(Calendar.DAY_OF_WEEK);
1260            mRule.appendTo(buffer, value != Calendar.SUNDAY ? value - 1 : 7);
1261        }
1262
1263        @Override
1264        public void appendTo(final Appendable buffer, final int value) throws IOException {
1265            mRule.appendTo(buffer, value);
1266        }
1267    }
1268
1269    /**
1270     * <p>Inner class to output the numeric day in week.</p>
1271     */
1272    private static class WeekYear implements NumberRule {
1273        private final NumberRule mRule;
1274
1275        WeekYear(final NumberRule rule) {
1276            mRule = rule;
1277        }
1278
1279        @Override
1280        public int estimateLength() {
1281            return mRule.estimateLength();
1282        }
1283
1284        @Override
1285        public void appendTo(final Appendable buffer, final Calendar calendar) throws IOException {
1286            mRule.appendTo(buffer, CalendarReflection.getWeekYear(calendar));
1287        }
1288
1289        @Override
1290        public void appendTo(final Appendable buffer, final int value) throws IOException {
1291            mRule.appendTo(buffer, value);
1292        }
1293    }
1294
1295    //-----------------------------------------------------------------------
1296
1297    private static final ConcurrentMap<TimeZoneDisplayKey, String> cTimeZoneDisplayCache =
1298        new ConcurrentHashMap<TimeZoneDisplayKey, String>(7);
1299    /**
1300     * <p>Gets the time zone display name, using a cache for performance.</p>
1301     *
1302     * @param tz  the zone to query
1303     * @param daylight  true if daylight savings
1304     * @param style  the style to use {@code TimeZone.LONG} or {@code TimeZone.SHORT}
1305     * @param locale  the locale to use
1306     * @return the textual name of the time zone
1307     */
1308    static String getTimeZoneDisplay(final TimeZone tz, final boolean daylight, final int style, final Locale locale) {
1309        final TimeZoneDisplayKey key = new TimeZoneDisplayKey(tz, daylight, style, locale);
1310        String value = cTimeZoneDisplayCache.get(key);
1311        if (value == null) {
1312            // This is a very slow call, so cache the results.
1313            value = tz.getDisplayName(daylight, style, locale);
1314            final String prior = cTimeZoneDisplayCache.putIfAbsent(key, value);
1315            if (prior != null) {
1316                value= prior;
1317            }
1318        }
1319        return value;
1320    }
1321
1322    /**
1323     * <p>Inner class to output a time zone name.</p>
1324     */
1325    private static class TimeZoneNameRule implements Rule {
1326        private final Locale mLocale;
1327        private final int mStyle;
1328        private final String mStandard;
1329        private final String mDaylight;
1330
1331        /**
1332         * Constructs an instance of {@code TimeZoneNameRule} with the specified properties.
1333         *
1334         * @param timeZone the time zone
1335         * @param locale the locale
1336         * @param style the style
1337         */
1338        TimeZoneNameRule(final TimeZone timeZone, final Locale locale, final int style) {
1339            mLocale = locale;
1340            mStyle = style;
1341            
1342            mStandard = getTimeZoneDisplay(timeZone, false, style, locale);
1343            mDaylight = getTimeZoneDisplay(timeZone, true, style, locale);
1344        }
1345
1346        /**
1347         * {@inheritDoc}
1348         */
1349        @Override
1350        public int estimateLength() {
1351            // We have no access to the Calendar object that will be passed to
1352            // appendTo so base estimate on the TimeZone passed to the
1353            // constructor
1354            return Math.max(mStandard.length(), mDaylight.length());
1355        }
1356
1357        /**
1358         * {@inheritDoc}
1359         */
1360        @Override
1361        public void appendTo(final Appendable buffer, final Calendar calendar) throws IOException {
1362            final TimeZone zone = calendar.getTimeZone();
1363            if (calendar.get(Calendar.DST_OFFSET) != 0) {
1364                buffer.append(getTimeZoneDisplay(zone, true, mStyle, mLocale));
1365            } else {
1366                buffer.append(getTimeZoneDisplay(zone, false, mStyle, mLocale));
1367            }
1368        }
1369    }
1370
1371    /**
1372     * <p>Inner class to output a time zone as a number {@code +/-HHMM}
1373     * or {@code +/-HH:MM}.</p>
1374     */
1375    private static class TimeZoneNumberRule implements Rule {
1376        static final TimeZoneNumberRule INSTANCE_COLON = new TimeZoneNumberRule(true);
1377        static final TimeZoneNumberRule INSTANCE_NO_COLON = new TimeZoneNumberRule(false);
1378        
1379        final boolean mColon;
1380
1381        /**
1382         * Constructs an instance of {@code TimeZoneNumberRule} with the specified properties.
1383         *
1384         * @param colon add colon between HH and MM in the output if {@code true}
1385         */
1386        TimeZoneNumberRule(final boolean colon) {
1387            mColon = colon;
1388        }
1389
1390        /**
1391         * {@inheritDoc}
1392         */
1393        @Override
1394        public int estimateLength() {
1395            return 5;
1396        }
1397
1398        /**
1399         * {@inheritDoc}
1400         */
1401        @Override
1402        public void appendTo(final Appendable buffer, final Calendar calendar) throws IOException {
1403            
1404            int offset = calendar.get(Calendar.ZONE_OFFSET) + calendar.get(Calendar.DST_OFFSET);
1405
1406            if (offset < 0) {
1407                buffer.append('-');
1408                offset = -offset;
1409            } else {
1410                buffer.append('+');
1411            }
1412
1413            final int hours = offset / (60 * 60 * 1000);
1414            appendDigits(buffer, hours);
1415
1416            if (mColon) {
1417                buffer.append(':');
1418            }
1419
1420            final int minutes = offset / (60 * 1000) - 60 * hours;
1421            appendDigits(buffer, minutes);
1422        }
1423    }
1424
1425    /**
1426     * <p>Inner class to output a time zone as a number {@code +/-HHMM}
1427     * or {@code +/-HH:MM}.</p>
1428     */
1429    private static class Iso8601_Rule implements Rule {
1430        
1431        // Sign TwoDigitHours or Z
1432        static final Iso8601_Rule ISO8601_HOURS = new Iso8601_Rule(3);       
1433        // Sign TwoDigitHours Minutes or Z
1434        static final Iso8601_Rule ISO8601_HOURS_MINUTES = new Iso8601_Rule(5);
1435        // Sign TwoDigitHours : Minutes or Z
1436        static final Iso8601_Rule ISO8601_HOURS_COLON_MINUTES = new Iso8601_Rule(6);
1437
1438        /**
1439         * Factory method for Iso8601_Rules.
1440         *
1441         * @param tokenLen a token indicating the length of the TimeZone String to be formatted.
1442         * @return a Iso8601_Rule that can format TimeZone String of length {@code tokenLen}. If no such
1443         *          rule exists, an IllegalArgumentException will be thrown.
1444         */
1445        static Iso8601_Rule getRule(int tokenLen) {
1446            switch(tokenLen) {
1447            case 1:
1448                return Iso8601_Rule.ISO8601_HOURS;
1449            case 2:
1450                return Iso8601_Rule.ISO8601_HOURS_MINUTES;
1451            case 3:
1452                return Iso8601_Rule.ISO8601_HOURS_COLON_MINUTES;
1453            default:
1454                throw new IllegalArgumentException("invalid number of X");                    
1455            }
1456        }        
1457        
1458        final int length;
1459
1460        /**
1461         * Constructs an instance of {@code Iso8601_Rule} with the specified properties.
1462         *
1463         * @param length The number of characters in output (unless Z is output)
1464         */
1465        Iso8601_Rule(final int length) {
1466            this.length = length;
1467        }
1468
1469        /**
1470         * {@inheritDoc}
1471         */
1472        @Override
1473        public int estimateLength() {
1474            return length;
1475        }
1476
1477        /**
1478         * {@inheritDoc}
1479         */
1480        @Override
1481        public void appendTo(final Appendable buffer, final Calendar calendar) throws IOException {
1482            int offset = calendar.get(Calendar.ZONE_OFFSET) + calendar.get(Calendar.DST_OFFSET);
1483            if (offset == 0) {
1484                buffer.append("Z");
1485                return;
1486            }
1487            
1488            if (offset < 0) {
1489                buffer.append('-');
1490                offset = -offset;
1491            } else {
1492                buffer.append('+');
1493            }
1494
1495            final int hours = offset / (60 * 60 * 1000);
1496            appendDigits(buffer, hours);
1497
1498            if (length<5) {
1499                return;
1500            }
1501            
1502            if (length==6) {
1503                buffer.append(':');
1504            }
1505
1506            final int minutes = offset / (60 * 1000) - 60 * hours;
1507            appendDigits(buffer, minutes);
1508        }
1509    }
1510
1511    // ----------------------------------------------------------------------
1512    /**
1513     * <p>Inner class that acts as a compound key for time zone names.</p>
1514     */
1515    private static class TimeZoneDisplayKey {
1516        private final TimeZone mTimeZone;
1517        private final int mStyle;
1518        private final Locale mLocale;
1519
1520        /**
1521         * Constructs an instance of {@code TimeZoneDisplayKey} with the specified properties.
1522         *
1523         * @param timeZone the time zone
1524         * @param daylight adjust the style for daylight saving time if {@code true}
1525         * @param style the timezone style
1526         * @param locale the timezone locale
1527         */
1528        TimeZoneDisplayKey(final TimeZone timeZone,
1529                           final boolean daylight, final int style, final Locale locale) {
1530            mTimeZone = timeZone;
1531            if (daylight) {
1532                mStyle = style | 0x80000000;
1533            } else {
1534                mStyle = style;
1535            }
1536            mLocale = locale;
1537        }
1538
1539        /**
1540         * {@inheritDoc}
1541         */
1542        @Override
1543        public int hashCode() {
1544            return (mStyle * 31 + mLocale.hashCode() ) * 31 + mTimeZone.hashCode();
1545        }
1546
1547        /**
1548         * {@inheritDoc}
1549         */
1550        @Override
1551        public boolean equals(final Object obj) {
1552            if (this == obj) {
1553                return true;
1554            }
1555            if (obj instanceof TimeZoneDisplayKey) {
1556                final TimeZoneDisplayKey other = (TimeZoneDisplayKey)obj;
1557                return
1558                    mTimeZone.equals(other.mTimeZone) &&
1559                    mStyle == other.mStyle &&
1560                    mLocale.equals(other.mLocale);
1561            }
1562            return false;
1563        }
1564    }
1565}