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.GregorianCalendar;
029import java.util.List;
030import java.util.Locale;
031import java.util.TimeZone;
032import java.util.concurrent.ConcurrentHashMap;
033import java.util.concurrent.ConcurrentMap;
034
035import org.apache.commons.lang3.Validate;
036
037/**
038 * <p>FastDatePrinter is a fast and thread-safe version of
039 * {@link java.text.SimpleDateFormat}.</p>
040 *
041 * <p>To obtain a proxy to a FastDatePrinter, use {@link FastDateFormat#getInstance(String, TimeZone, Locale)} 
042 * or another variation of the factory methods of {@link FastDateFormat}.</p>
043 * 
044 * <p>Since FastDatePrinter is thread safe, you can use a static member instance:</p>
045 * <code>
046 *     private static final DatePrinter DATE_PRINTER = FastDateFormat.getInstance("yyyy-MM-dd");
047 * </code>
048 * 
049 * <p>This class can be used as a direct replacement to
050 * {@code SimpleDateFormat} in most formatting situations.
051 * This class is especially useful in multi-threaded server environments.
052 * {@code SimpleDateFormat} is not thread-safe in any JDK version,
053 * nor will it be as Sun have closed the bug/RFE.
054 * </p>
055 *
056 * <p>Only formatting is supported by this class, but all patterns are compatible with
057 * SimpleDateFormat (except time zones and some year patterns - see below).</p>
058 *
059 * <p>Java 1.4 introduced a new pattern letter, {@code 'Z'}, to represent
060 * time zones in RFC822 format (eg. {@code +0800} or {@code -1100}).
061 * This pattern letter can be used here (on all JDK versions).</p>
062 *
063 * <p>In addition, the pattern {@code 'ZZ'} has been made to represent
064 * ISO 8601 full format time zones (eg. {@code +08:00} or {@code -11:00}).
065 * This introduces a minor incompatibility with Java 1.4, but at a gain of
066 * useful functionality.</p>
067 *
068 * <p>Javadoc cites for the year pattern: <i>For formatting, if the number of
069 * pattern letters is 2, the year is truncated to 2 digits; otherwise it is
070 * interpreted as a number.</i> Starting with Java 1.7 a pattern of 'Y' or
071 * 'YYY' will be formatted as '2003', while it was '03' in former Java
072 * versions. FastDatePrinter implements the behavior of Java 7.</p>
073 *
074 * @version $Id: FastDatePrinter.java 1666568 2015-03-13 20:29:06Z britter $
075 * @since 3.2
076 * @see FastDateParser
077 */
078public class FastDatePrinter implements DatePrinter, Serializable {
079    // A lot of the speed in this class comes from caching, but some comes
080    // from the special int to StringBuffer conversion.
081    //
082    // The following produces a padded 2 digit number:
083    //   buffer.append((char)(value / 10 + '0'));
084    //   buffer.append((char)(value % 10 + '0'));
085    //
086    // Note that the fastest append to StringBuffer is a single char (used here).
087    // Note that Integer.toString() is not called, the conversion is simply
088    // taking the value and adding (mathematically) the ASCII value for '0'.
089    // So, don't change this code! It works and is very fast.
090
091    /**
092     * Required for serialization support.
093     *
094     * @see java.io.Serializable
095     */
096    private static final long serialVersionUID = 1L;
097
098    /**
099     * FULL locale dependent date or time style.
100     */
101    public static final int FULL = DateFormat.FULL;
102    /**
103     * LONG locale dependent date or time style.
104     */
105    public static final int LONG = DateFormat.LONG;
106    /**
107     * MEDIUM locale dependent date or time style.
108     */
109    public static final int MEDIUM = DateFormat.MEDIUM;
110    /**
111     * SHORT locale dependent date or time style.
112     */
113    public static final int SHORT = DateFormat.SHORT;
114
115    /**
116     * The pattern.
117     */
118    private final String mPattern;
119    /**
120     * The time zone.
121     */
122    private final TimeZone mTimeZone;
123    /**
124     * The locale.
125     */
126    private final Locale mLocale;
127    /**
128     * The parsed rules.
129     */
130    private transient Rule[] mRules;
131    /**
132     * The estimated maximum length.
133     */
134    private transient int mMaxLengthEstimate;
135
136    // Constructor
137    //-----------------------------------------------------------------------
138    /**
139     * <p>Constructs a new FastDatePrinter.</p>
140     *
141     * @param pattern  {@link java.text.SimpleDateFormat} compatible pattern
142     * @param timeZone  non-null time zone to use
143     * @param locale  non-null locale to use
144     * @throws NullPointerException if pattern, timeZone, or locale is null.
145     */
146    protected FastDatePrinter(final String pattern, final TimeZone timeZone, final Locale locale) {
147        mPattern = pattern;
148        mTimeZone = timeZone;
149        mLocale = locale;
150
151        init();
152    }
153
154    /**
155     * <p>Initializes the instance for first use.</p>
156     */
157    private void init() {
158        final List<Rule> rulesList = parsePattern();
159        mRules = rulesList.toArray(new Rule[rulesList.size()]);
160
161        int len = 0;
162        for (int i=mRules.length; --i >= 0; ) {
163            len += mRules[i].estimateLength();
164        }
165
166        mMaxLengthEstimate = len;
167    }
168
169    // Parse the pattern
170    //-----------------------------------------------------------------------
171    /**
172     * <p>Returns a list of Rules given a pattern.</p>
173     *
174     * @return a {@code List} of Rule objects
175     * @throws IllegalArgumentException if pattern is invalid
176     */
177    protected List<Rule> parsePattern() {
178        final DateFormatSymbols symbols = new DateFormatSymbols(mLocale);
179        final List<Rule> rules = new ArrayList<Rule>();
180
181        final String[] ERAs = symbols.getEras();
182        final String[] months = symbols.getMonths();
183        final String[] shortMonths = symbols.getShortMonths();
184        final String[] weekdays = symbols.getWeekdays();
185        final String[] shortWeekdays = symbols.getShortWeekdays();
186        final String[] AmPmStrings = symbols.getAmPmStrings();
187
188        final int length = mPattern.length();
189        final int[] indexRef = new int[1];
190
191        for (int i = 0; i < length; i++) {
192            indexRef[0] = i;
193            final String token = parseToken(mPattern, indexRef);
194            i = indexRef[0];
195
196            final int tokenLen = token.length();
197            if (tokenLen == 0) {
198                break;
199            }
200
201            Rule rule;
202            final char c = token.charAt(0);
203
204            switch (c) {
205            case 'G': // era designator (text)
206                rule = new TextField(Calendar.ERA, ERAs);
207                break;
208            case 'y': // year (number)
209                if (tokenLen == 2) {
210                    rule = TwoDigitYearField.INSTANCE;
211                } else {
212                    rule = selectNumberRule(Calendar.YEAR, tokenLen < 4 ? 4 : tokenLen);
213                }
214                break;
215            case 'M': // month in year (text and number)
216                if (tokenLen >= 4) {
217                    rule = new TextField(Calendar.MONTH, months);
218                } else if (tokenLen == 3) {
219                    rule = new TextField(Calendar.MONTH, shortMonths);
220                } else if (tokenLen == 2) {
221                    rule = TwoDigitMonthField.INSTANCE;
222                } else {
223                    rule = UnpaddedMonthField.INSTANCE;
224                }
225                break;
226            case 'd': // day in month (number)
227                rule = selectNumberRule(Calendar.DAY_OF_MONTH, tokenLen);
228                break;
229            case 'h': // hour in am/pm (number, 1..12)
230                rule = new TwelveHourField(selectNumberRule(Calendar.HOUR, tokenLen));
231                break;
232            case 'H': // hour in day (number, 0..23)
233                rule = selectNumberRule(Calendar.HOUR_OF_DAY, tokenLen);
234                break;
235            case 'm': // minute in hour (number)
236                rule = selectNumberRule(Calendar.MINUTE, tokenLen);
237                break;
238            case 's': // second in minute (number)
239                rule = selectNumberRule(Calendar.SECOND, tokenLen);
240                break;
241            case 'S': // millisecond (number)
242                rule = selectNumberRule(Calendar.MILLISECOND, tokenLen);
243                break;
244            case 'E': // day in week (text)
245                rule = new TextField(Calendar.DAY_OF_WEEK, tokenLen < 4 ? shortWeekdays : weekdays);
246                break;
247            case 'D': // day in year (number)
248                rule = selectNumberRule(Calendar.DAY_OF_YEAR, tokenLen);
249                break;
250            case 'F': // day of week in month (number)
251                rule = selectNumberRule(Calendar.DAY_OF_WEEK_IN_MONTH, tokenLen);
252                break;
253            case 'w': // week in year (number)
254                rule = selectNumberRule(Calendar.WEEK_OF_YEAR, tokenLen);
255                break;
256            case 'W': // week in month (number)
257                rule = selectNumberRule(Calendar.WEEK_OF_MONTH, tokenLen);
258                break;
259            case 'a': // am/pm marker (text)
260                rule = new TextField(Calendar.AM_PM, AmPmStrings);
261                break;
262            case 'k': // hour in day (1..24)
263                rule = new TwentyFourHourField(selectNumberRule(Calendar.HOUR_OF_DAY, tokenLen));
264                break;
265            case 'K': // hour in am/pm (0..11)
266                rule = selectNumberRule(Calendar.HOUR, tokenLen);
267                break;
268            case 'z': // time zone (text)
269                if (tokenLen >= 4) {
270                    rule = new TimeZoneNameRule(mTimeZone, mLocale, TimeZone.LONG);
271                } else {
272                    rule = new TimeZoneNameRule(mTimeZone, mLocale, TimeZone.SHORT);
273                }
274                break;
275            case 'Z': // time zone (value)
276                if (tokenLen == 1) {
277                    rule = TimeZoneNumberRule.INSTANCE_NO_COLON;
278                } else if (tokenLen == 2) {
279                    rule = TimeZoneNumberRule.INSTANCE_ISO_8601;
280                } else {
281                    rule = TimeZoneNumberRule.INSTANCE_COLON;
282                }
283                break;
284            case '\'': // literal text
285                final String sub = token.substring(1);
286                if (sub.length() == 1) {
287                    rule = new CharacterLiteral(sub.charAt(0));
288                } else {
289                    rule = new StringLiteral(sub);
290                }
291                break;
292            default:
293                throw new IllegalArgumentException("Illegal pattern component: " + token);
294            }
295
296            rules.add(rule);
297        }
298
299        return rules;
300    }
301
302    /**
303     * <p>Performs the parsing of tokens.</p>
304     *
305     * @param pattern  the pattern
306     * @param indexRef  index references
307     * @return parsed token
308     */
309    protected String parseToken(final String pattern, final int[] indexRef) {
310        final StringBuilder buf = new StringBuilder();
311
312        int i = indexRef[0];
313        final int length = pattern.length();
314
315        char c = pattern.charAt(i);
316        if (c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z') {
317            // Scan a run of the same character, which indicates a time
318            // pattern.
319            buf.append(c);
320
321            while (i + 1 < length) {
322                final char peek = pattern.charAt(i + 1);
323                if (peek == c) {
324                    buf.append(c);
325                    i++;
326                } else {
327                    break;
328                }
329            }
330        } else {
331            // This will identify token as text.
332            buf.append('\'');
333
334            boolean inLiteral = false;
335
336            for (; i < length; i++) {
337                c = pattern.charAt(i);
338
339                if (c == '\'') {
340                    if (i + 1 < length && pattern.charAt(i + 1) == '\'') {
341                        // '' is treated as escaped '
342                        i++;
343                        buf.append(c);
344                    } else {
345                        inLiteral = !inLiteral;
346                    }
347                } else if (!inLiteral &&
348                         (c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z')) {
349                    i--;
350                    break;
351                } else {
352                    buf.append(c);
353                }
354            }
355        }
356
357        indexRef[0] = i;
358        return buf.toString();
359    }
360
361    /**
362     * <p>Gets an appropriate rule for the padding required.</p>
363     *
364     * @param field  the field to get a rule for
365     * @param padding  the padding required
366     * @return a new rule with the correct padding
367     */
368    protected NumberRule selectNumberRule(final int field, final int padding) {
369        switch (padding) {
370        case 1:
371            return new UnpaddedNumberField(field);
372        case 2:
373            return new TwoDigitNumberField(field);
374        default:
375            return new PaddedNumberField(field, padding);
376        }
377    }
378
379    // Format methods
380    //-----------------------------------------------------------------------
381    /**
382     * <p>Formats a {@code Date}, {@code Calendar} or
383     * {@code Long} (milliseconds) object.</p>
384     *
385     * @param obj  the object to format
386     * @param toAppendTo  the buffer to append to
387     * @param pos  the position - ignored
388     * @return the buffer passed in
389     */
390    @Override
391    public StringBuffer format(final Object obj, final StringBuffer toAppendTo, final FieldPosition pos) {
392        if (obj instanceof Date) {
393            return format((Date) obj, toAppendTo);
394        } else if (obj instanceof Calendar) {
395            return format((Calendar) obj, toAppendTo);
396        } else if (obj instanceof Long) {
397            return format(((Long) obj).longValue(), toAppendTo);
398        } else {
399            throw new IllegalArgumentException("Unknown class: " +
400                (obj == null ? "<null>" : obj.getClass().getName()));
401        }
402    }
403
404    /* (non-Javadoc)
405     * @see org.apache.commons.lang3.time.DatePrinter#format(long)
406     */
407    @Override
408    public String format(final long millis) {
409        final Calendar c = newCalendar();  // hard code GregorianCalendar
410        c.setTimeInMillis(millis);
411        return applyRulesToString(c);
412    }
413
414    /**
415     * Creates a String representation of the given Calendar by applying the rules of this printer to it.
416     * @param c the Calender to apply the rules to.
417     * @return a String representation of the given Calendar.
418     */
419    private String applyRulesToString(final Calendar c) {
420        return applyRules(c, new StringBuffer(mMaxLengthEstimate)).toString();
421    }
422
423    /**
424     * Creation method for ne calender instances.
425     * @return a new Calendar instance.
426     */
427    private GregorianCalendar newCalendar() {
428        // hard code GregorianCalendar
429        return new GregorianCalendar(mTimeZone, mLocale);
430    }
431
432    /* (non-Javadoc)
433     * @see org.apache.commons.lang3.time.DatePrinter#format(java.util.Date)
434     */
435    @Override
436    public String format(final Date date) {
437        final Calendar c = newCalendar();  // hard code GregorianCalendar
438        c.setTime(date);
439        return applyRulesToString(c);
440    }
441
442    /* (non-Javadoc)
443     * @see org.apache.commons.lang3.time.DatePrinter#format(java.util.Calendar)
444     */
445    @Override
446    public String format(final Calendar calendar) {
447        return format(calendar, new StringBuffer(mMaxLengthEstimate)).toString();
448    }
449
450    /* (non-Javadoc)
451     * @see org.apache.commons.lang3.time.DatePrinter#format(long, java.lang.StringBuffer)
452     */
453    @Override
454    public StringBuffer format(final long millis, final StringBuffer buf) {
455        return format(new Date(millis), buf);
456    }
457
458    /* (non-Javadoc)
459     * @see org.apache.commons.lang3.time.DatePrinter#format(java.util.Date, java.lang.StringBuffer)
460     */
461    @Override
462    public StringBuffer format(final Date date, final StringBuffer buf) {
463        final Calendar c = newCalendar();  // hard code GregorianCalendar
464        c.setTime(date);
465        return applyRules(c, buf);
466    }
467
468    /* (non-Javadoc)
469     * @see org.apache.commons.lang3.time.DatePrinter#format(java.util.Calendar, java.lang.StringBuffer)
470     */
471    @Override
472    public StringBuffer format(final Calendar calendar, final StringBuffer buf) {
473        return applyRules(calendar, buf);
474    }
475
476    /**
477     * <p>Performs the formatting by applying the rules to the
478     * specified calendar.</p>
479     *
480     * @param calendar  the calendar to format
481     * @param buf  the buffer to format into
482     * @return the specified string buffer
483     */
484    protected StringBuffer applyRules(final Calendar calendar, final StringBuffer buf) {
485        for (final Rule rule : mRules) {
486            rule.appendTo(buf, calendar);
487        }
488        return buf;
489    }
490
491    // Accessors
492    //-----------------------------------------------------------------------
493    /* (non-Javadoc)
494     * @see org.apache.commons.lang3.time.DatePrinter#getPattern()
495     */
496    @Override
497    public String getPattern() {
498        return mPattern;
499    }
500
501    /* (non-Javadoc)
502     * @see org.apache.commons.lang3.time.DatePrinter#getTimeZone()
503     */
504    @Override
505    public TimeZone getTimeZone() {
506        return mTimeZone;
507    }
508
509    /* (non-Javadoc)
510     * @see org.apache.commons.lang3.time.DatePrinter#getLocale()
511     */
512    @Override
513    public Locale getLocale() {
514        return mLocale;
515    }
516
517    /**
518     * <p>Gets an estimate for the maximum string length that the
519     * formatter will produce.</p>
520     *
521     * <p>The actual formatted length will almost always be less than or
522     * equal to this amount.</p>
523     *
524     * @return the maximum formatted length
525     */
526    public int getMaxLengthEstimate() {
527        return mMaxLengthEstimate;
528    }
529
530    // Basics
531    //-----------------------------------------------------------------------
532    /**
533     * <p>Compares two objects for equality.</p>
534     *
535     * @param obj  the object to compare to
536     * @return {@code true} if equal
537     */
538    @Override
539    public boolean equals(final Object obj) {
540        if (obj instanceof FastDatePrinter == false) {
541            return false;
542        }
543        final FastDatePrinter other = (FastDatePrinter) obj;
544        return mPattern.equals(other.mPattern)
545            && mTimeZone.equals(other.mTimeZone) 
546            && mLocale.equals(other.mLocale);
547    }
548
549    /**
550     * <p>Returns a hashcode compatible with equals.</p>
551     *
552     * @return a hashcode compatible with equals
553     */
554    @Override
555    public int hashCode() {
556        return mPattern.hashCode() + 13 * (mTimeZone.hashCode() + 13 * mLocale.hashCode());
557    }
558
559    /**
560     * <p>Gets a debugging string version of this formatter.</p>
561     *
562     * @return a debugging string
563     */
564    @Override
565    public String toString() {
566        return "FastDatePrinter[" + mPattern + "," + mLocale + "," + mTimeZone.getID() + "]";
567    }
568
569    // Serializing
570    //-----------------------------------------------------------------------
571    /**
572     * Create the object after serialization. This implementation reinitializes the
573     * transient properties.
574     *
575     * @param in ObjectInputStream from which the object is being deserialized.
576     * @throws IOException if there is an IO issue.
577     * @throws ClassNotFoundException if a class cannot be found.
578     */
579    private void readObject(final ObjectInputStream in) throws IOException, ClassNotFoundException {
580        in.defaultReadObject();
581        init();
582    }
583
584    // Rules
585    //-----------------------------------------------------------------------
586    /**
587     * <p>Inner class defining a rule.</p>
588     */
589    private interface Rule {
590        /**
591         * Returns the estimated lentgh of the result.
592         *
593         * @return the estimated length
594         */
595        int estimateLength();
596
597        /**
598         * Appends the value of the specified calendar to the output buffer based on the rule implementation.
599         *
600         * @param buffer the output buffer
601         * @param calendar calendar to be appended
602         */
603        void appendTo(StringBuffer buffer, Calendar calendar);
604    }
605
606    /**
607     * <p>Inner class defining a numeric rule.</p>
608     */
609    private interface NumberRule extends Rule {
610        /**
611         * Appends the specified value to the output buffer based on the rule implementation.
612         *
613         * @param buffer the output buffer
614         * @param value the value to be appended
615         */
616        void appendTo(StringBuffer buffer, int value);
617    }
618
619    /**
620     * <p>Inner class to output a constant single character.</p>
621     */
622    private static class CharacterLiteral implements Rule {
623        private final char mValue;
624
625        /**
626         * Constructs a new instance of {@code CharacterLiteral}
627         * to hold the specified value.
628         *
629         * @param value the character literal
630         */
631        CharacterLiteral(final char value) {
632            mValue = value;
633        }
634
635        /**
636         * {@inheritDoc}
637         */
638        @Override
639        public int estimateLength() {
640            return 1;
641        }
642
643        /**
644         * {@inheritDoc}
645         */
646        @Override
647        public void appendTo(final StringBuffer buffer, final Calendar calendar) {
648            buffer.append(mValue);
649        }
650    }
651
652    /**
653     * <p>Inner class to output a constant string.</p>
654     */
655    private static class StringLiteral implements Rule {
656        private final String mValue;
657
658        /**
659         * Constructs a new instance of {@code StringLiteral}
660         * to hold the specified value.
661         *
662         * @param value the string literal
663         */
664        StringLiteral(final String value) {
665            mValue = value;
666        }
667
668        /**
669         * {@inheritDoc}
670         */
671        @Override
672        public int estimateLength() {
673            return mValue.length();
674        }
675
676        /**
677         * {@inheritDoc}
678         */
679        @Override
680        public void appendTo(final StringBuffer buffer, final Calendar calendar) {
681            buffer.append(mValue);
682        }
683    }
684
685    /**
686     * <p>Inner class to output one of a set of values.</p>
687     */
688    private static class TextField implements Rule {
689        private final int mField;
690        private final String[] mValues;
691
692        /**
693         * Constructs an instance of {@code TextField}
694         * with the specified field and values.
695         *
696         * @param field the field
697         * @param values the field values
698         */
699        TextField(final int field, final String[] values) {
700            mField = field;
701            mValues = values;
702        }
703
704        /**
705         * {@inheritDoc}
706         */
707        @Override
708        public int estimateLength() {
709            int max = 0;
710            for (int i=mValues.length; --i >= 0; ) {
711                final int len = mValues[i].length();
712                if (len > max) {
713                    max = len;
714                }
715            }
716            return max;
717        }
718
719        /**
720         * {@inheritDoc}
721         */
722        @Override
723        public void appendTo(final StringBuffer buffer, final Calendar calendar) {
724            buffer.append(mValues[calendar.get(mField)]);
725        }
726    }
727
728    /**
729     * <p>Inner class to output an unpadded number.</p>
730     */
731    private static class UnpaddedNumberField implements NumberRule {
732        private final int mField;
733
734        /**
735         * Constructs an instance of {@code UnpadedNumberField} with the specified field.
736         *
737         * @param field the field
738         */
739        UnpaddedNumberField(final int field) {
740            mField = field;
741        }
742
743        /**
744         * {@inheritDoc}
745         */
746        @Override
747        public int estimateLength() {
748            return 4;
749        }
750
751        /**
752         * {@inheritDoc}
753         */
754        @Override
755        public void appendTo(final StringBuffer buffer, final Calendar calendar) {
756            appendTo(buffer, calendar.get(mField));
757        }
758
759        /**
760         * {@inheritDoc}
761         */
762        @Override
763        public final void appendTo(final StringBuffer buffer, final int value) {
764            if (value < 10) {
765                buffer.append((char)(value + '0'));
766            } else if (value < 100) {
767                buffer.append((char)(value / 10 + '0'));
768                buffer.append((char)(value % 10 + '0'));
769            } else {
770                buffer.append(Integer.toString(value));
771            }
772        }
773    }
774
775    /**
776     * <p>Inner class to output an unpadded month.</p>
777     */
778    private static class UnpaddedMonthField implements NumberRule {
779        static final UnpaddedMonthField INSTANCE = new UnpaddedMonthField();
780
781        /**
782         * Constructs an instance of {@code UnpaddedMonthField}.
783         *
784         */
785        UnpaddedMonthField() {
786            super();
787        }
788
789        /**
790         * {@inheritDoc}
791         */
792        @Override
793        public int estimateLength() {
794            return 2;
795        }
796
797        /**
798         * {@inheritDoc}
799         */
800        @Override
801        public void appendTo(final StringBuffer buffer, final Calendar calendar) {
802            appendTo(buffer, calendar.get(Calendar.MONTH) + 1);
803        }
804
805        /**
806         * {@inheritDoc}
807         */
808        @Override
809        public final void appendTo(final StringBuffer buffer, final int value) {
810            if (value < 10) {
811                buffer.append((char)(value + '0'));
812            } else {
813                buffer.append((char)(value / 10 + '0'));
814                buffer.append((char)(value % 10 + '0'));
815            }
816        }
817    }
818
819    /**
820     * <p>Inner class to output a padded number.</p>
821     */
822    private static class PaddedNumberField implements NumberRule {
823        private final int mField;
824        private final int mSize;
825
826        /**
827         * Constructs an instance of {@code PaddedNumberField}.
828         *
829         * @param field the field
830         * @param size size of the output field
831         */
832        PaddedNumberField(final int field, final int size) {
833            if (size < 3) {
834                // Should use UnpaddedNumberField or TwoDigitNumberField.
835                throw new IllegalArgumentException();
836            }
837            mField = field;
838            mSize = size;
839        }
840
841        /**
842         * {@inheritDoc}
843         */
844        @Override
845        public int estimateLength() {
846            return 4;
847        }
848
849        /**
850         * {@inheritDoc}
851         */
852        @Override
853        public void appendTo(final StringBuffer buffer, final Calendar calendar) {
854            appendTo(buffer, calendar.get(mField));
855        }
856
857        /**
858         * {@inheritDoc}
859         */
860        @Override
861        public final void appendTo(final StringBuffer buffer, final int value) {
862            if (value < 100) {
863                for (int i = mSize; --i >= 2; ) {
864                    buffer.append('0');
865                }
866                buffer.append((char)(value / 10 + '0'));
867                buffer.append((char)(value % 10 + '0'));
868            } else {
869                int digits;
870                if (value < 1000) {
871                    digits = 3;
872                } else {
873                    Validate.isTrue(value > -1, "Negative values should not be possible", value);
874                    digits = Integer.toString(value).length();
875                }
876                for (int i = mSize; --i >= digits; ) {
877                    buffer.append('0');
878                }
879                buffer.append(Integer.toString(value));
880            }
881        }
882    }
883
884    /**
885     * <p>Inner class to output a two digit number.</p>
886     */
887    private static class TwoDigitNumberField implements NumberRule {
888        private final int mField;
889
890        /**
891         * Constructs an instance of {@code TwoDigitNumberField} with the specified field.
892         *
893         * @param field the field
894         */
895        TwoDigitNumberField(final int field) {
896            mField = field;
897        }
898
899        /**
900         * {@inheritDoc}
901         */
902        @Override
903        public int estimateLength() {
904            return 2;
905        }
906
907        /**
908         * {@inheritDoc}
909         */
910        @Override
911        public void appendTo(final StringBuffer buffer, final Calendar calendar) {
912            appendTo(buffer, calendar.get(mField));
913        }
914
915        /**
916         * {@inheritDoc}
917         */
918        @Override
919        public final void appendTo(final StringBuffer buffer, final int value) {
920            if (value < 100) {
921                buffer.append((char)(value / 10 + '0'));
922                buffer.append((char)(value % 10 + '0'));
923            } else {
924                buffer.append(Integer.toString(value));
925            }
926        }
927    }
928
929    /**
930     * <p>Inner class to output a two digit year.</p>
931     */
932    private static class TwoDigitYearField implements NumberRule {
933        static final TwoDigitYearField INSTANCE = new TwoDigitYearField();
934
935        /**
936         * Constructs an instance of {@code TwoDigitYearField}.
937         */
938        TwoDigitYearField() {
939            super();
940        }
941
942        /**
943         * {@inheritDoc}
944         */
945        @Override
946        public int estimateLength() {
947            return 2;
948        }
949
950        /**
951         * {@inheritDoc}
952         */
953        @Override
954        public void appendTo(final StringBuffer buffer, final Calendar calendar) {
955            appendTo(buffer, calendar.get(Calendar.YEAR) % 100);
956        }
957
958        /**
959         * {@inheritDoc}
960         */
961        @Override
962        public final void appendTo(final StringBuffer buffer, final int value) {
963            buffer.append((char)(value / 10 + '0'));
964            buffer.append((char)(value % 10 + '0'));
965        }
966    }
967
968    /**
969     * <p>Inner class to output a two digit month.</p>
970     */
971    private static class TwoDigitMonthField implements NumberRule {
972        static final TwoDigitMonthField INSTANCE = new TwoDigitMonthField();
973
974        /**
975         * Constructs an instance of {@code TwoDigitMonthField}.
976         */
977        TwoDigitMonthField() {
978            super();
979        }
980
981        /**
982         * {@inheritDoc}
983         */
984        @Override
985        public int estimateLength() {
986            return 2;
987        }
988
989        /**
990         * {@inheritDoc}
991         */
992        @Override
993        public void appendTo(final StringBuffer buffer, final Calendar calendar) {
994            appendTo(buffer, calendar.get(Calendar.MONTH) + 1);
995        }
996
997        /**
998         * {@inheritDoc}
999         */
1000        @Override
1001        public final void appendTo(final StringBuffer buffer, final int value) {
1002            buffer.append((char)(value / 10 + '0'));
1003            buffer.append((char)(value % 10 + '0'));
1004        }
1005    }
1006
1007    /**
1008     * <p>Inner class to output the twelve hour field.</p>
1009     */
1010    private static class TwelveHourField implements NumberRule {
1011        private final NumberRule mRule;
1012
1013        /**
1014         * Constructs an instance of {@code TwelveHourField} with the specified
1015         * {@code NumberRule}.
1016         *
1017         * @param rule the rule
1018         */
1019        TwelveHourField(final NumberRule rule) {
1020            mRule = rule;
1021        }
1022
1023        /**
1024         * {@inheritDoc}
1025         */
1026        @Override
1027        public int estimateLength() {
1028            return mRule.estimateLength();
1029        }
1030
1031        /**
1032         * {@inheritDoc}
1033         */
1034        @Override
1035        public void appendTo(final StringBuffer buffer, final Calendar calendar) {
1036            int value = calendar.get(Calendar.HOUR);
1037            if (value == 0) {
1038                value = calendar.getLeastMaximum(Calendar.HOUR) + 1;
1039            }
1040            mRule.appendTo(buffer, value);
1041        }
1042
1043        /**
1044         * {@inheritDoc}
1045         */
1046        @Override
1047        public void appendTo(final StringBuffer buffer, final int value) {
1048            mRule.appendTo(buffer, value);
1049        }
1050    }
1051
1052    /**
1053     * <p>Inner class to output the twenty four hour field.</p>
1054     */
1055    private static class TwentyFourHourField implements NumberRule {
1056        private final NumberRule mRule;
1057
1058        /**
1059         * Constructs an instance of {@code TwentyFourHourField} with the specified
1060         * {@code NumberRule}.
1061         *
1062         * @param rule the rule
1063         */
1064        TwentyFourHourField(final NumberRule rule) {
1065            mRule = rule;
1066        }
1067
1068        /**
1069         * {@inheritDoc}
1070         */
1071        @Override
1072        public int estimateLength() {
1073            return mRule.estimateLength();
1074        }
1075
1076        /**
1077         * {@inheritDoc}
1078         */
1079        @Override
1080        public void appendTo(final StringBuffer buffer, final Calendar calendar) {
1081            int value = calendar.get(Calendar.HOUR_OF_DAY);
1082            if (value == 0) {
1083                value = calendar.getMaximum(Calendar.HOUR_OF_DAY) + 1;
1084            }
1085            mRule.appendTo(buffer, value);
1086        }
1087
1088        /**
1089         * {@inheritDoc}
1090         */
1091        @Override
1092        public void appendTo(final StringBuffer buffer, final int value) {
1093            mRule.appendTo(buffer, value);
1094        }
1095    }
1096
1097    //-----------------------------------------------------------------------
1098
1099    private static final ConcurrentMap<TimeZoneDisplayKey, String> cTimeZoneDisplayCache =
1100        new ConcurrentHashMap<TimeZoneDisplayKey, String>(7);
1101    /**
1102     * <p>Gets the time zone display name, using a cache for performance.</p>
1103     *
1104     * @param tz  the zone to query
1105     * @param daylight  true if daylight savings
1106     * @param style  the style to use {@code TimeZone.LONG} or {@code TimeZone.SHORT}
1107     * @param locale  the locale to use
1108     * @return the textual name of the time zone
1109     */
1110    static String getTimeZoneDisplay(final TimeZone tz, final boolean daylight, final int style, final Locale locale) {
1111        final TimeZoneDisplayKey key = new TimeZoneDisplayKey(tz, daylight, style, locale);
1112        String value = cTimeZoneDisplayCache.get(key);
1113        if (value == null) {
1114            // This is a very slow call, so cache the results.
1115            value = tz.getDisplayName(daylight, style, locale);
1116            final String prior = cTimeZoneDisplayCache.putIfAbsent(key, value);
1117            if (prior != null) {
1118                value= prior;
1119            }
1120        }
1121        return value;
1122    }
1123
1124    /**
1125     * <p>Inner class to output a time zone name.</p>
1126     */
1127    private static class TimeZoneNameRule implements Rule {
1128        private final Locale mLocale;
1129        private final int mStyle;
1130        private final String mStandard;
1131        private final String mDaylight;
1132
1133        /**
1134         * Constructs an instance of {@code TimeZoneNameRule} with the specified properties.
1135         *
1136         * @param timeZone the time zone
1137         * @param locale the locale
1138         * @param style the style
1139         */
1140        TimeZoneNameRule(final TimeZone timeZone, final Locale locale, final int style) {
1141            mLocale = locale;
1142            mStyle = style;
1143            
1144            mStandard = getTimeZoneDisplay(timeZone, false, style, locale);
1145            mDaylight = getTimeZoneDisplay(timeZone, true, style, locale);
1146        }
1147
1148        /**
1149         * {@inheritDoc}
1150         */
1151        @Override
1152        public int estimateLength() {
1153            // We have no access to the Calendar object that will be passed to
1154            // appendTo so base estimate on the TimeZone passed to the
1155            // constructor
1156            return Math.max(mStandard.length(), mDaylight.length());
1157        }
1158
1159        /**
1160         * {@inheritDoc}
1161         */
1162        @Override
1163        public void appendTo(final StringBuffer buffer, final Calendar calendar) {
1164            final TimeZone zone = calendar.getTimeZone();
1165            if (calendar.get(Calendar.DST_OFFSET) != 0) {
1166                buffer.append(getTimeZoneDisplay(zone, true, mStyle, mLocale));
1167            } else {
1168                buffer.append(getTimeZoneDisplay(zone, false, mStyle, mLocale));
1169            }
1170        }
1171    }
1172
1173    /**
1174     * <p>Inner class to output a time zone as a number {@code +/-HHMM}
1175     * or {@code +/-HH:MM}.</p>
1176     */
1177    private static class TimeZoneNumberRule implements Rule {
1178        static final TimeZoneNumberRule INSTANCE_COLON = new TimeZoneNumberRule(true, false);
1179        static final TimeZoneNumberRule INSTANCE_NO_COLON = new TimeZoneNumberRule(false, false);
1180        static final TimeZoneNumberRule INSTANCE_ISO_8601 = new TimeZoneNumberRule(true, true);
1181
1182        final boolean mColon;
1183        final boolean mISO8601;
1184
1185        /**
1186         * Constructs an instance of {@code TimeZoneNumberRule} with the specified properties.
1187         *
1188         * @param colon add colon between HH and MM in the output if {@code true}
1189         * @param iso8601 create an ISO 8601 format output
1190         */
1191        TimeZoneNumberRule(final boolean colon, final boolean iso8601) {
1192            mColon = colon;
1193            mISO8601 = iso8601;
1194        }
1195
1196        /**
1197         * {@inheritDoc}
1198         */
1199        @Override
1200        public int estimateLength() {
1201            return 5;
1202        }
1203
1204        /**
1205         * {@inheritDoc}
1206         */
1207        @Override
1208        public void appendTo(final StringBuffer buffer, final Calendar calendar) {
1209            if (mISO8601 && calendar.getTimeZone().getID().equals("UTC")) {
1210                buffer.append("Z");
1211                return;
1212            }
1213            
1214            int offset = calendar.get(Calendar.ZONE_OFFSET) + calendar.get(Calendar.DST_OFFSET);
1215
1216            if (offset < 0) {
1217                buffer.append('-');
1218                offset = -offset;
1219            } else {
1220                buffer.append('+');
1221            }
1222
1223            final int hours = offset / (60 * 60 * 1000);
1224            buffer.append((char)(hours / 10 + '0'));
1225            buffer.append((char)(hours % 10 + '0'));
1226
1227            if (mColon) {
1228                buffer.append(':');
1229            }
1230
1231            final int minutes = offset / (60 * 1000) - 60 * hours;
1232            buffer.append((char)(minutes / 10 + '0'));
1233            buffer.append((char)(minutes % 10 + '0'));
1234        }
1235    }
1236
1237    // ----------------------------------------------------------------------
1238    /**
1239     * <p>Inner class that acts as a compound key for time zone names.</p>
1240     */
1241    private static class TimeZoneDisplayKey {
1242        private final TimeZone mTimeZone;
1243        private final int mStyle;
1244        private final Locale mLocale;
1245
1246        /**
1247         * Constructs an instance of {@code TimeZoneDisplayKey} with the specified properties.
1248         *
1249         * @param timeZone the time zone
1250         * @param daylight adjust the style for daylight saving time if {@code true}
1251         * @param style the timezone style
1252         * @param locale the timezone locale
1253         */
1254        TimeZoneDisplayKey(final TimeZone timeZone,
1255                           final boolean daylight, final int style, final Locale locale) {
1256            mTimeZone = timeZone;
1257            if (daylight) {
1258                mStyle = style | 0x80000000;
1259            } else {
1260                mStyle = style;
1261            }
1262            mLocale = locale;
1263        }
1264
1265        /**
1266         * {@inheritDoc}
1267         */
1268        @Override
1269        public int hashCode() {
1270            return (mStyle * 31 + mLocale.hashCode() ) * 31 + mTimeZone.hashCode();
1271        }
1272
1273        /**
1274         * {@inheritDoc}
1275         */
1276        @Override
1277        public boolean equals(final Object obj) {
1278            if (this == obj) {
1279                return true;
1280            }
1281            if (obj instanceof TimeZoneDisplayKey) {
1282                final TimeZoneDisplayKey other = (TimeZoneDisplayKey)obj;
1283                return
1284                    mTimeZone.equals(other.mTimeZone) &&
1285                    mStyle == other.mStyle &&
1286                    mLocale.equals(other.mLocale);
1287            }
1288            return false;
1289        }
1290    }
1291}