diff --git a/TMessagesProj/src/main/java/org/telegram/android/FastDateFormat.java b/TMessagesProj/src/main/java/org/telegram/android/FastDateFormat.java deleted file mode 100644 index 0d0a029a..00000000 --- a/TMessagesProj/src/main/java/org/telegram/android/FastDateFormat.java +++ /dev/null @@ -1,1731 +0,0 @@ -/* - * This is the source code of Telegram for Android v. 1.3.2. - * It is licensed under GNU GPL v. 2 or later. - * You should have received a copy of the license in this archive (see LICENSE). - * - * Copyright Nikolai Kudashov, 2013. - */ -package org.telegram.android; - -import java.io.IOException; -import java.io.ObjectInputStream; -import java.text.DateFormat; -import java.text.DateFormatSymbols; -import java.text.FieldPosition; -import java.text.Format; -import java.text.ParsePosition; -import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.Calendar; -import java.util.Date; -import java.util.GregorianCalendar; -import java.util.HashMap; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.TimeZone; - -/** - *
FastDateFormat is a fast and thread-safe version of - * {@link java.text.SimpleDateFormat}.
- * - *This class can be used as a direct replacement to
- * SimpleDateFormat
in most formatting situations.
- * This class is especially useful in multi-threaded server environments.
- * SimpleDateFormat
is not thread-safe in any JDK version,
- * nor will it be as Sun have closed the bug/RFE.
- *
Only formatting is supported, but all patterns are compatible with - * SimpleDateFormat (except time zones - see below).
- * - *Java 1.4 introduced a new pattern letter, 'Z'
, to represent
- * time zones in RFC822 format (eg. +0800
or -1100
).
- * This pattern letter can be used here (on all JDK versions).
In addition, the pattern 'ZZ'
has been made to represent
- * ISO8601 full format time zones (eg. +08:00
or -11:00
).
- * This introduces a minor incompatibility with Java 1.4, but at a gain of
- * useful functionality.
Gets a formatter instance using the default pattern in the - * default locale.
- * - * @return a date/time formatter - */ - public static FastDateFormat getInstance() { - return getInstance(getDefaultPattern(), null, null); - } - - /** - *Gets a formatter instance using the specified pattern in the - * default locale.
- * - * @param pattern {@link java.text.SimpleDateFormat} compatible - * pattern - * @return a pattern based date/time formatter - * @throws IllegalArgumentException if pattern is invalid - */ - public static FastDateFormat getInstance(String pattern) { - return getInstance(pattern, null, null); - } - - /** - *Gets a formatter instance using the specified pattern and - * time zone.
- * - * @param pattern {@link java.text.SimpleDateFormat} compatible - * pattern - * @param timeZone optional time zone, overrides time zone of - * formatted date - * @return a pattern based date/time formatter - * @throws IllegalArgumentException if pattern is invalid - */ - public static FastDateFormat getInstance(String pattern, TimeZone timeZone) { - return getInstance(pattern, timeZone, null); - } - - /** - *Gets a formatter instance using the specified pattern and - * locale.
- * - * @param pattern {@link java.text.SimpleDateFormat} compatible - * pattern - * @param locale optional locale, overrides system locale - * @return a pattern based date/time formatter - * @throws IllegalArgumentException if pattern is invalid - */ - public static FastDateFormat getInstance(String pattern, Locale locale) { - return getInstance(pattern, null, locale); - } - - /** - *Gets a formatter instance using the specified pattern, time zone - * and locale.
- * - * @param pattern {@link java.text.SimpleDateFormat} compatible - * pattern - * @param timeZone optional time zone, overrides time zone of - * formatted date - * @param locale optional locale, overrides system locale - * @return a pattern based date/time formatter - * @throws IllegalArgumentException if pattern is invalid - * ornull
- */
- public static synchronized FastDateFormat getInstance(String pattern, TimeZone timeZone, Locale locale) {
- FastDateFormat emptyFormat = new FastDateFormat(pattern, timeZone, locale);
- FastDateFormat format = (FastDateFormat) cInstanceCache.get(emptyFormat);
- if (format == null) {
- format = emptyFormat;
- format.init(); // convert shell format into usable one
- cInstanceCache.put(format, format); // this is OK!
- }
- return format;
- }
-
- //-----------------------------------------------------------------------
- /**
- * Gets a date formatter instance using the specified style in the - * default time zone and locale.
- * - * @param style date style: FULL, LONG, MEDIUM, or SHORT - * @return a localized standard date formatter - * @throws IllegalArgumentException if the Locale has no date - * pattern defined - * @since 2.1 - */ - public static FastDateFormat getDateInstance(int style) { - return getDateInstance(style, null, null); - } - - /** - *Gets a date formatter instance using the specified style and - * locale in the default time zone.
- * - * @param style date style: FULL, LONG, MEDIUM, or SHORT - * @param locale optional locale, overrides system locale - * @return a localized standard date formatter - * @throws IllegalArgumentException if the Locale has no date - * pattern defined - * @since 2.1 - */ - public static FastDateFormat getDateInstance(int style, Locale locale) { - return getDateInstance(style, null, locale); - } - - /** - *Gets a date formatter instance using the specified style and - * time zone in the default locale.
- * - * @param style date style: FULL, LONG, MEDIUM, or SHORT - * @param timeZone optional time zone, overrides time zone of - * formatted date - * @return a localized standard date formatter - * @throws IllegalArgumentException if the Locale has no date - * pattern defined - * @since 2.1 - */ - public static FastDateFormat getDateInstance(int style, TimeZone timeZone) { - return getDateInstance(style, timeZone, null); - } - /** - *Gets a date formatter instance using the specified style, time - * zone and locale.
- * - * @param style date style: FULL, LONG, MEDIUM, or SHORT - * @param timeZone optional time zone, overrides time zone of - * formatted date - * @param locale optional locale, overrides system locale - * @return a localized standard date formatter - * @throws IllegalArgumentException if the Locale has no date - * pattern defined - */ - public static synchronized FastDateFormat getDateInstance(int style, TimeZone timeZone, Locale locale) { - Object key = new Integer(style); - if (timeZone != null) { - key = new Pair(key, timeZone); - } - - if (locale == null) { - locale = Locale.getDefault(); - } - - key = new Pair(key, locale); - - FastDateFormat format = (FastDateFormat) cDateInstanceCache.get(key); - if (format == null) { - try { - SimpleDateFormat formatter = (SimpleDateFormat) DateFormat.getDateInstance(style, locale); - String pattern = formatter.toPattern(); - format = getInstance(pattern, timeZone, locale); - cDateInstanceCache.put(key, format); - - } catch (ClassCastException ex) { - throw new IllegalArgumentException("No date pattern for locale: " + locale); - } - } - return format; - } - - //----------------------------------------------------------------------- - /** - *Gets a time formatter instance using the specified style in the - * default time zone and locale.
- * - * @param style time style: FULL, LONG, MEDIUM, or SHORT - * @return a localized standard time formatter - * @throws IllegalArgumentException if the Locale has no time - * pattern defined - * @since 2.1 - */ - public static FastDateFormat getTimeInstance(int style) { - return getTimeInstance(style, null, null); - } - - /** - *Gets a time formatter instance using the specified style and - * locale in the default time zone.
- * - * @param style time style: FULL, LONG, MEDIUM, or SHORT - * @param locale optional locale, overrides system locale - * @return a localized standard time formatter - * @throws IllegalArgumentException if the Locale has no time - * pattern defined - * @since 2.1 - */ - public static FastDateFormat getTimeInstance(int style, Locale locale) { - return getTimeInstance(style, null, locale); - } - - /** - *Gets a time formatter instance using the specified style and - * time zone in the default locale.
- * - * @param style time style: FULL, LONG, MEDIUM, or SHORT - * @param timeZone optional time zone, overrides time zone of - * formatted time - * @return a localized standard time formatter - * @throws IllegalArgumentException if the Locale has no time - * pattern defined - * @since 2.1 - */ - public static FastDateFormat getTimeInstance(int style, TimeZone timeZone) { - return getTimeInstance(style, timeZone, null); - } - - /** - *Gets a time formatter instance using the specified style, time - * zone and locale.
- * - * @param style time style: FULL, LONG, MEDIUM, or SHORT - * @param timeZone optional time zone, overrides time zone of - * formatted time - * @param locale optional locale, overrides system locale - * @return a localized standard time formatter - * @throws IllegalArgumentException if the Locale has no time - * pattern defined - */ - public static synchronized FastDateFormat getTimeInstance(int style, TimeZone timeZone, Locale locale) { - Object key = new Integer(style); - if (timeZone != null) { - key = new Pair(key, timeZone); - } - if (locale != null) { - key = new Pair(key, locale); - } - - FastDateFormat format = (FastDateFormat) cTimeInstanceCache.get(key); - if (format == null) { - if (locale == null) { - locale = Locale.getDefault(); - } - - try { - SimpleDateFormat formatter = (SimpleDateFormat) DateFormat.getTimeInstance(style, locale); - String pattern = formatter.toPattern(); - format = getInstance(pattern, timeZone, locale); - cTimeInstanceCache.put(key, format); - - } catch (ClassCastException ex) { - throw new IllegalArgumentException("No date pattern for locale: " + locale); - } - } - return format; - } - - //----------------------------------------------------------------------- - /** - *Gets a date/time formatter instance using the specified style - * in the default time zone and locale.
- * - * @param dateStyle date style: FULL, LONG, MEDIUM, or SHORT - * @param timeStyle time style: FULL, LONG, MEDIUM, or SHORT - * @return a localized standard date/time formatter - * @throws IllegalArgumentException if the Locale has no date/time - * pattern defined - * @since 2.1 - */ - public static FastDateFormat getDateTimeInstance( - int dateStyle, int timeStyle) { - return getDateTimeInstance(dateStyle, timeStyle, null, null); - } - - /** - *Gets a date/time formatter instance using the specified style and - * locale in the default time zone.
- * - * @param dateStyle date style: FULL, LONG, MEDIUM, or SHORT - * @param timeStyle time style: FULL, LONG, MEDIUM, or SHORT - * @param locale optional locale, overrides system locale - * @return a localized standard date/time formatter - * @throws IllegalArgumentException if the Locale has no date/time - * pattern defined - * @since 2.1 - */ - public static FastDateFormat getDateTimeInstance( - int dateStyle, int timeStyle, Locale locale) { - return getDateTimeInstance(dateStyle, timeStyle, null, locale); - } - - /** - *Gets a date/time formatter instance using the specified style and - * time zone in the default locale.
- * - * @param dateStyle date style: FULL, LONG, MEDIUM, or SHORT - * @param timeStyle time style: FULL, LONG, MEDIUM, or SHORT - * @param timeZone optional time zone, overrides time zone of - * formatted date - * @return a localized standard date/time formatter - * @throws IllegalArgumentException if the Locale has no date/time - * pattern defined - * @since 2.1 - */ - public static FastDateFormat getDateTimeInstance( - int dateStyle, int timeStyle, TimeZone timeZone) { - return getDateTimeInstance(dateStyle, timeStyle, timeZone, null); - } - /** - *Gets a date/time formatter instance using the specified style, - * time zone and locale.
- * - * @param dateStyle date style: FULL, LONG, MEDIUM, or SHORT - * @param timeStyle time style: FULL, LONG, MEDIUM, or SHORT - * @param timeZone optional time zone, overrides time zone of - * formatted date - * @param locale optional locale, overrides system locale - * @return a localized standard date/time formatter - * @throws IllegalArgumentException if the Locale has no date/time - * pattern defined - */ - public static synchronized FastDateFormat getDateTimeInstance(int dateStyle, int timeStyle, TimeZone timeZone, - Locale locale) { - - Object key = new Pair(new Integer(dateStyle), new Integer(timeStyle)); - if (timeZone != null) { - key = new Pair(key, timeZone); - } - if (locale == null) { - locale = Locale.getDefault(); - } - key = new Pair(key, locale); - - FastDateFormat format = (FastDateFormat) cDateTimeInstanceCache.get(key); - if (format == null) { - try { - SimpleDateFormat formatter = (SimpleDateFormat) DateFormat.getDateTimeInstance(dateStyle, timeStyle, - locale); - String pattern = formatter.toPattern(); - format = getInstance(pattern, timeZone, locale); - cDateTimeInstanceCache.put(key, format); - - } catch (ClassCastException ex) { - throw new IllegalArgumentException("No date time pattern for locale: " + locale); - } - } - return format; - } - - //----------------------------------------------------------------------- - /** - *Gets the time zone display name, using a cache for performance.
- * - * @param tz the zone to query - * @param daylight true if daylight savings - * @param style the style to useTimeZone.LONG
- * or TimeZone.SHORT
- * @param locale the locale to use
- * @return the textual name of the time zone
- */
- static synchronized String getTimeZoneDisplay(TimeZone tz, boolean daylight, int style, Locale locale) {
- Object key = new TimeZoneDisplayKey(tz, daylight, style, locale);
- String value = (String) cTimeZoneDisplayCache.get(key);
- if (value == null) {
- // This is a very slow call, so cache the results.
- value = tz.getDisplayName(daylight, style, locale);
- cTimeZoneDisplayCache.put(key, value);
- }
- return value;
- }
-
- /**
- * Gets the default pattern.
- * - * @return the default pattern - */ - private static synchronized String getDefaultPattern() { - if (cDefaultPattern == null) { - cDefaultPattern = new SimpleDateFormat().toPattern(); - } - return cDefaultPattern; - } - - // Constructor - //----------------------------------------------------------------------- - /** - *Constructs a new FastDateFormat.
- * - * @param pattern {@link java.text.SimpleDateFormat} compatible - * pattern - * @param timeZone time zone to use,null
means use
- * default for Date
and value within for
- * Calendar
- * @param locale locale, null
means use system
- * default
- * @throws IllegalArgumentException if pattern is invalid or
- * null
- */
- protected FastDateFormat(String pattern, TimeZone timeZone, Locale locale) {
- super();
- if (pattern == null) {
- throw new IllegalArgumentException("The pattern must not be null");
- }
- mPattern = pattern;
-
- mTimeZoneForced = (timeZone != null);
- if (timeZone == null) {
- timeZone = TimeZone.getDefault();
- }
- mTimeZone = timeZone;
-
- mLocaleForced = (locale != null);
- if (locale == null) {
- locale = Locale.getDefault();
- }
- mLocale = locale;
- }
-
- /**
- * Initializes the instance for first use.
- */ - protected void init() { - List rulesList = parsePattern(); - mRules = (Rule[]) rulesList.toArray(new Rule[rulesList.size()]); - - int len = 0; - for (int i=mRules.length; --i >= 0; ) { - len += mRules[i].estimateLength(); - } - - mMaxLengthEstimate = len; - } - - // Parse the pattern - //----------------------------------------------------------------------- - /** - *Returns a list of Rules given a pattern.
- * - * @return aList
of Rule objects
- * @throws IllegalArgumentException if pattern is invalid
- */
- protected List parsePattern() {
- DateFormatSymbols symbols = new DateFormatSymbols(mLocale);
- List rules = new ArrayList();
-
- String[] ERAs = symbols.getEras();
- String[] months = symbols.getMonths();
- String[] shortMonths = symbols.getShortMonths();
- String[] weekdays = symbols.getWeekdays();
- String[] shortWeekdays = symbols.getShortWeekdays();
- String[] AmPmStrings = symbols.getAmPmStrings();
-
- int length = mPattern.length();
- int[] indexRef = new int[1];
-
- for (int i = 0; i < length; i++) {
- indexRef[0] = i;
- String token = parseToken(mPattern, indexRef);
- i = indexRef[0];
-
- int tokenLen = token.length();
- if (tokenLen == 0) {
- break;
- }
-
- Rule rule;
- char c = token.charAt(0);
-
- switch (c) {
- case 'G': // era designator (text)
- rule = new TextField(Calendar.ERA, ERAs);
- break;
- case 'y': // year (number)
- if (tokenLen >= 4) {
- rule = selectNumberRule(Calendar.YEAR, tokenLen);
- } else {
- rule = TwoDigitYearField.INSTANCE;
- }
- break;
- case 'M': // month in year (text and number)
- if (tokenLen >= 4) {
- rule = new TextField(Calendar.MONTH, months);
- } else if (tokenLen == 3) {
- rule = new TextField(Calendar.MONTH, shortMonths);
- } else if (tokenLen == 2) {
- rule = TwoDigitMonthField.INSTANCE;
- } else {
- rule = UnpaddedMonthField.INSTANCE;
- }
- break;
- case 'd': // day in month (number)
- rule = selectNumberRule(Calendar.DAY_OF_MONTH, tokenLen);
- break;
- case 'h': // hour in am/pm (number, 1..12)
- rule = new TwelveHourField(selectNumberRule(Calendar.HOUR, tokenLen));
- break;
- case 'H': // hour in day (number, 0..23)
- rule = selectNumberRule(Calendar.HOUR_OF_DAY, tokenLen);
- break;
- case 'm': // minute in hour (number)
- rule = selectNumberRule(Calendar.MINUTE, tokenLen);
- break;
- case 's': // second in minute (number)
- rule = selectNumberRule(Calendar.SECOND, tokenLen);
- break;
- case 'S': // millisecond (number)
- rule = selectNumberRule(Calendar.MILLISECOND, tokenLen);
- break;
- case 'E': // day in week (text)
- rule = new TextField(Calendar.DAY_OF_WEEK, tokenLen < 4 ? shortWeekdays : weekdays);
- break;
- case 'D': // day in year (number)
- rule = selectNumberRule(Calendar.DAY_OF_YEAR, tokenLen);
- break;
- case 'F': // day of week in month (number)
- rule = selectNumberRule(Calendar.DAY_OF_WEEK_IN_MONTH, tokenLen);
- break;
- case 'w': // week in year (number)
- rule = selectNumberRule(Calendar.WEEK_OF_YEAR, tokenLen);
- break;
- case 'W': // week in month (number)
- rule = selectNumberRule(Calendar.WEEK_OF_MONTH, tokenLen);
- break;
- case 'a': // am/pm marker (text)
- rule = new TextField(Calendar.AM_PM, AmPmStrings);
- break;
- case 'k': // hour in day (1..24)
- rule = new TwentyFourHourField(selectNumberRule(Calendar.HOUR_OF_DAY, tokenLen));
- break;
- case 'K': // hour in am/pm (0..11)
- rule = selectNumberRule(Calendar.HOUR, tokenLen);
- break;
- case 'z': // time zone (text)
- if (tokenLen >= 4) {
- rule = new TimeZoneNameRule(mTimeZone, mTimeZoneForced, mLocale, TimeZone.LONG);
- } else {
- rule = new TimeZoneNameRule(mTimeZone, mTimeZoneForced, mLocale, TimeZone.SHORT);
- }
- break;
- case 'Z': // time zone (value)
- if (tokenLen == 1) {
- rule = TimeZoneNumberRule.INSTANCE_NO_COLON;
- } else {
- rule = TimeZoneNumberRule.INSTANCE_COLON;
- }
- break;
- case '\'': // literal text
- String sub = token.substring(1);
- if (sub.length() == 1) {
- rule = new CharacterLiteral(sub.charAt(0));
- } else {
- rule = new StringLiteral(sub);
- }
- break;
- default:
- throw new IllegalArgumentException("Illegal pattern component: " + token);
- }
-
- rules.add(rule);
- }
-
- return rules;
- }
-
- /**
- * Performs the parsing of tokens.
- * - * @param pattern the pattern - * @param indexRef index references - * @return parsed token - */ - protected String parseToken(String pattern, int[] indexRef) { - StringBuffer buf = new StringBuffer(); - - int i = indexRef[0]; - int length = pattern.length(); - - char c = pattern.charAt(i); - if (c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z') { - // Scan a run of the same character, which indicates a time - // pattern. - buf.append(c); - - while (i + 1 < length) { - char peek = pattern.charAt(i + 1); - if (peek == c) { - buf.append(c); - i++; - } else { - break; - } - } - } else { - // This will identify token as text. - buf.append('\''); - - boolean inLiteral = false; - - for (; i < length; i++) { - c = pattern.charAt(i); - - if (c == '\'') { - if (i + 1 < length && pattern.charAt(i + 1) == '\'') { - // '' is treated as escaped ' - i++; - buf.append(c); - } else { - inLiteral = !inLiteral; - } - } else if (!inLiteral && - (c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z')) { - i--; - break; - } else { - buf.append(c); - } - } - } - - indexRef[0] = i; - return buf.toString(); - } - - /** - *Gets an appropriate rule for the padding required.
- * - * @param field the field to get a rule for - * @param padding the padding required - * @return a new rule with the correct padding - */ - protected NumberRule selectNumberRule(int field, int padding) { - switch (padding) { - case 1: - return new UnpaddedNumberField(field); - case 2: - return new TwoDigitNumberField(field); - default: - return new PaddedNumberField(field, padding); - } - } - - // Format methods - //----------------------------------------------------------------------- - /** - *Formats a Date
, Calendar
or
- * Long
(milliseconds) object.
Formats a millisecond long
value.
Formats a Date
object.
Formats a Calendar
object.
Formats a milliseond long
value into the
- * supplied StringBuffer
.
Formats a Date
object into the
- * supplied StringBuffer
.
Formats a Calendar
object into the
- * supplied StringBuffer
.
Performs the formatting by applying the rules to the - * specified calendar.
- * - * @param calendar the calendar to format - * @param buf the buffer to format into - * @return the specified string buffer - */ - protected StringBuffer applyRules(Calendar calendar, StringBuffer buf) { - Rule[] rules = mRules; - int len = mRules.length; - for (int i = 0; i < len; i++) { - rules[i].appendTo(buf, calendar); - } - return buf; - } - - // Parsing - //----------------------------------------------------------------------- - /** - *Parsing is not supported.
- * - * @param source the string to parse - * @param pos the parsing position - * @returnnull
as not supported
- */
- public Object parseObject(String source, ParsePosition pos) {
- pos.setIndex(0);
- pos.setErrorIndex(0);
- return null;
- }
-
- // Accessors
- //-----------------------------------------------------------------------
- /**
- * Gets the pattern used by this formatter.
- * - * @return the pattern, {@link java.text.SimpleDateFormat} compatible - */ - public String getPattern() { - return mPattern; - } - - /** - *Gets the time zone used by this formatter.
- * - *This zone is always used for Date
formatting.
- * If a Calendar
is passed in to be formatted, the
- * time zone on that may be used depending on
- * {@link #getTimeZoneOverridesCalendar()}.
Returns true
if the time zone of the
- * calendar overrides the time zone of the formatter.
true
if time zone of formatter
- * overridden for calendars
- */
- public boolean getTimeZoneOverridesCalendar() {
- return mTimeZoneForced;
- }
-
- /**
- * Gets the locale used by this formatter.
- * - * @return the locale - */ - public Locale getLocale() { - return mLocale; - } - - /** - *Gets an estimate for the maximum string length that the - * formatter will produce.
- * - *The actual formatted length will almost always be less than or - * equal to this amount.
- * - * @return the maximum formatted length - */ - public int getMaxLengthEstimate() { - return mMaxLengthEstimate; - } - - // Basics - //----------------------------------------------------------------------- - /** - *Compares two objects for equality.
- * - * @param obj the object to compare to - * @returntrue
if equal
- */
- public boolean equals(Object obj) {
- if (!(obj instanceof FastDateFormat)) {
- return false;
- }
- FastDateFormat other = (FastDateFormat) obj;
- return (mPattern == other.mPattern || mPattern.equals(other.mPattern)) &&
- (mTimeZone == other.mTimeZone || mTimeZone.equals(other.mTimeZone)) &&
- (mLocale == other.mLocale || mLocale.equals(other.mLocale)) &&
- (mTimeZoneForced == other.mTimeZoneForced) &&
- (mLocaleForced == other.mLocaleForced);
- }
-
- /**
- * Returns a hashcode compatible with equals.
- * - * @return a hashcode compatible with equals - */ - public int hashCode() { - int total = 0; - total += mPattern.hashCode(); - total += mTimeZone.hashCode(); - total += (mTimeZoneForced ? 1 : 0); - total += mLocale.hashCode(); - total += (mLocaleForced ? 1 : 0); - return total; - } - - /** - *Gets a debugging string version of this formatter.
- * - * @return a debugging string - */ - public String toString() { - return "FastDateFormat[" + mPattern + "]"; - } - - // Serializing - //----------------------------------------------------------------------- - /** - * Create the object after serialization. This implementation reinitializes the - * transient properties. - * - * @param in ObjectInputStream from which the object is being deserialized. - * @throws IOException if there is an IO issue. - * @throws ClassNotFoundException if a class cannot be found. - */ - private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { - in.defaultReadObject(); - init(); - } - - // Rules - //----------------------------------------------------------------------- - /** - *Inner class defining a rule.
- */ - private interface Rule { - /** - * Returns the estimated lentgh of the result. - * - * @return the estimated length - */ - int estimateLength(); - - /** - * Appends the value of the specified calendar to the output buffer based on the rule implementation. - * - * @param buffer the output buffer - * @param calendar calendar to be appended - */ - void appendTo(StringBuffer buffer, Calendar calendar); - } - - /** - *Inner class defining a numeric rule.
- */ - private interface NumberRule extends Rule { - /** - * Appends the specified value to the output buffer based on the rule implementation. - * - * @param buffer the output buffer - * @param value the value to be appended - */ - void appendTo(StringBuffer buffer, int value); - } - - /** - *Inner class to output a constant single character.
- */ - private static class CharacterLiteral implements Rule { - private final char mValue; - - /** - * Constructs a new instance ofCharacterLiteral
- * to hold the specified value.
- *
- * @param value the character literal
- */
- CharacterLiteral(char value) {
- mValue = value;
- }
-
- /**
- * {@inheritDoc}
- */
- public int estimateLength() {
- return 1;
- }
-
- /**
- * {@inheritDoc}
- */
- public void appendTo(StringBuffer buffer, Calendar calendar) {
- buffer.append(mValue);
- }
- }
-
- /**
- * Inner class to output a constant string.
- */ - private static class StringLiteral implements Rule { - private final String mValue; - - /** - * Constructs a new instance ofStringLiteral
- * to hold the specified value.
- *
- * @param value the string literal
- */
- StringLiteral(String value) {
- mValue = value;
- }
-
- /**
- * {@inheritDoc}
- */
- public int estimateLength() {
- return mValue.length();
- }
-
- /**
- * {@inheritDoc}
- */
- public void appendTo(StringBuffer buffer, Calendar calendar) {
- buffer.append(mValue);
- }
- }
-
- /**
- * Inner class to output one of a set of values.
- */ - private static class TextField implements Rule { - private final int mField; - private final String[] mValues; - - /** - * Constructs an instance ofTextField
- * with the specified field and values.
- *
- * @param field the field
- * @param values the field values
- */
- TextField(int field, String[] values) {
- mField = field;
- mValues = values;
- }
-
- /**
- * {@inheritDoc}
- */
- public int estimateLength() {
- int max = 0;
- for (int i=mValues.length; --i >= 0; ) {
- int len = mValues[i].length();
- if (len > max) {
- max = len;
- }
- }
- return max;
- }
-
- /**
- * {@inheritDoc}
- */
- public void appendTo(StringBuffer buffer, Calendar calendar) {
- buffer.append(mValues[calendar.get(mField)]);
- }
- }
-
- /**
- * Inner class to output an unpadded number.
- */ - private static class UnpaddedNumberField implements NumberRule { - static final UnpaddedNumberField INSTANCE_YEAR = new UnpaddedNumberField(Calendar.YEAR); - - private final int mField; - - /** - * Constructs an instance ofUnpadedNumberField
with the specified field.
- *
- * @param field the field
- */
- UnpaddedNumberField(int field) {
- mField = field;
- }
-
- /**
- * {@inheritDoc}
- */
- public int estimateLength() {
- return 4;
- }
-
- /**
- * {@inheritDoc}
- */
- public void appendTo(StringBuffer buffer, Calendar calendar) {
- appendTo(buffer, calendar.get(mField));
- }
-
- /**
- * {@inheritDoc}
- */
- public final void appendTo(StringBuffer buffer, int value) {
- if (value < 10) {
- buffer.append((char)(value + '0'));
- } else if (value < 100) {
- buffer.append((char)(value / 10 + '0'));
- buffer.append((char)(value % 10 + '0'));
- } else {
- buffer.append(Integer.toString(value));
- }
- }
- }
-
- /**
- * Inner class to output an unpadded month.
- */ - private static class UnpaddedMonthField implements NumberRule { - static final UnpaddedMonthField INSTANCE = new UnpaddedMonthField(); - - /** - * Constructs an instance ofUnpaddedMonthField
.
- *
- */
- UnpaddedMonthField() {
- super();
- }
-
- /**
- * {@inheritDoc}
- */
- public int estimateLength() {
- return 2;
- }
-
- /**
- * {@inheritDoc}
- */
- public void appendTo(StringBuffer buffer, Calendar calendar) {
- appendTo(buffer, calendar.get(Calendar.MONTH) + 1);
- }
-
- /**
- * {@inheritDoc}
- */
- public final void appendTo(StringBuffer buffer, int value) {
- if (value < 10) {
- buffer.append((char)(value + '0'));
- } else {
- buffer.append((char)(value / 10 + '0'));
- buffer.append((char)(value % 10 + '0'));
- }
- }
- }
-
- /**
- * Inner class to output a padded number.
- */ - private static class PaddedNumberField implements NumberRule { - private final int mField; - private final int mSize; - - /** - * Constructs an instance ofPaddedNumberField
.
- *
- * @param field the field
- * @param size size of the output field
- */
- PaddedNumberField(int field, int size) {
- if (size < 3) {
- // Should use UnpaddedNumberField or TwoDigitNumberField.
- throw new IllegalArgumentException();
- }
- mField = field;
- mSize = size;
- }
-
- /**
- * {@inheritDoc}
- */
- public int estimateLength() {
- return 4;
- }
-
- /**
- * {@inheritDoc}
- */
- public void appendTo(StringBuffer buffer, Calendar calendar) {
- appendTo(buffer, calendar.get(mField));
- }
-
- /**
- * {@inheritDoc}
- */
- public final void appendTo(StringBuffer buffer, int value) {
- if (value < 100) {
- for (int i = mSize; --i >= 2; ) {
- buffer.append('0');
- }
- buffer.append((char)(value / 10 + '0'));
- buffer.append((char)(value % 10 + '0'));
- } else {
- int digits;
- if (value < 1000) {
- digits = 3;
- } else {
- //Validate.isTrue(value > -1, "Negative values should not be possible", value);
- digits = Integer.toString(value).length();
- }
- for (int i = mSize; --i >= digits; ) {
- buffer.append('0');
- }
- buffer.append(Integer.toString(value));
- }
- }
- }
-
- /**
- * Inner class to output a two digit number.
- */ - private static class TwoDigitNumberField implements NumberRule { - private final int mField; - - /** - * Constructs an instance ofTwoDigitNumberField
with the specified field.
- *
- * @param field the field
- */
- TwoDigitNumberField(int field) {
- mField = field;
- }
-
- /**
- * {@inheritDoc}
- */
- public int estimateLength() {
- return 2;
- }
-
- /**
- * {@inheritDoc}
- */
- public void appendTo(StringBuffer buffer, Calendar calendar) {
- appendTo(buffer, calendar.get(mField));
- }
-
- /**
- * {@inheritDoc}
- */
- public final void appendTo(StringBuffer buffer, int value) {
- if (value < 100) {
- buffer.append((char)(value / 10 + '0'));
- buffer.append((char)(value % 10 + '0'));
- } else {
- buffer.append(Integer.toString(value));
- }
- }
- }
-
- /**
- * Inner class to output a two digit year.
- */ - private static class TwoDigitYearField implements NumberRule { - static final TwoDigitYearField INSTANCE = new TwoDigitYearField(); - - /** - * Constructs an instance ofTwoDigitYearField
.
- */
- TwoDigitYearField() {
- super();
- }
-
- /**
- * {@inheritDoc}
- */
- public int estimateLength() {
- return 2;
- }
-
- /**
- * {@inheritDoc}
- */
- public void appendTo(StringBuffer buffer, Calendar calendar) {
- appendTo(buffer, calendar.get(Calendar.YEAR) % 100);
- }
-
- /**
- * {@inheritDoc}
- */
- public final void appendTo(StringBuffer buffer, int value) {
- buffer.append((char)(value / 10 + '0'));
- buffer.append((char)(value % 10 + '0'));
- }
- }
-
- /**
- * Inner class to output a two digit month.
- */ - private static class TwoDigitMonthField implements NumberRule { - static final TwoDigitMonthField INSTANCE = new TwoDigitMonthField(); - - /** - * Constructs an instance ofTwoDigitMonthField
.
- */
- TwoDigitMonthField() {
- super();
- }
-
- /**
- * {@inheritDoc}
- */
- public int estimateLength() {
- return 2;
- }
-
- /**
- * {@inheritDoc}
- */
- public void appendTo(StringBuffer buffer, Calendar calendar) {
- appendTo(buffer, calendar.get(Calendar.MONTH) + 1);
- }
-
- /**
- * {@inheritDoc}
- */
- public final void appendTo(StringBuffer buffer, int value) {
- buffer.append((char)(value / 10 + '0'));
- buffer.append((char)(value % 10 + '0'));
- }
- }
-
- /**
- * Inner class to output the twelve hour field.
- */ - private static class TwelveHourField implements NumberRule { - private final NumberRule mRule; - - /** - * Constructs an instance ofTwelveHourField
with the specified
- * NumberRule
.
- *
- * @param rule the rule
- */
- TwelveHourField(NumberRule rule) {
- mRule = rule;
- }
-
- /**
- * {@inheritDoc}
- */
- public int estimateLength() {
- return mRule.estimateLength();
- }
-
- /**
- * {@inheritDoc}
- */
- public void appendTo(StringBuffer buffer, Calendar calendar) {
- int value = calendar.get(Calendar.HOUR);
- if (value == 0) {
- value = calendar.getLeastMaximum(Calendar.HOUR) + 1;
- }
- mRule.appendTo(buffer, value);
- }
-
- /**
- * {@inheritDoc}
- */
- public void appendTo(StringBuffer buffer, int value) {
- mRule.appendTo(buffer, value);
- }
- }
-
- /**
- * Inner class to output the twenty four hour field.
- */ - private static class TwentyFourHourField implements NumberRule { - private final NumberRule mRule; - - /** - * Constructs an instance ofTwentyFourHourField
with the specified
- * NumberRule
.
- *
- * @param rule the rule
- */
- TwentyFourHourField(NumberRule rule) {
- mRule = rule;
- }
-
- /**
- * {@inheritDoc}
- */
- public int estimateLength() {
- return mRule.estimateLength();
- }
-
- /**
- * {@inheritDoc}
- */
- public void appendTo(StringBuffer buffer, Calendar calendar) {
- int value = calendar.get(Calendar.HOUR_OF_DAY);
- if (value == 0) {
- value = calendar.getMaximum(Calendar.HOUR_OF_DAY) + 1;
- }
- mRule.appendTo(buffer, value);
- }
-
- /**
- * {@inheritDoc}
- */
- public void appendTo(StringBuffer buffer, int value) {
- mRule.appendTo(buffer, value);
- }
- }
-
- /**
- * Inner class to output a time zone name.
- */ - private static class TimeZoneNameRule implements Rule { - private final TimeZone mTimeZone; - private final boolean mTimeZoneForced; - private final Locale mLocale; - private final int mStyle; - private final String mStandard; - private final String mDaylight; - - /** - * Constructs an instance ofTimeZoneNameRule
with the specified properties.
- *
- * @param timeZone the time zone
- * @param timeZoneForced if true
the time zone is forced into standard and daylight
- * @param locale the locale
- * @param style the style
- */
- TimeZoneNameRule(TimeZone timeZone, boolean timeZoneForced, Locale locale, int style) {
- mTimeZone = timeZone;
- mTimeZoneForced = timeZoneForced;
- mLocale = locale;
- mStyle = style;
-
- if (timeZoneForced) {
- mStandard = getTimeZoneDisplay(timeZone, false, style, locale);
- mDaylight = getTimeZoneDisplay(timeZone, true, style, locale);
- } else {
- mStandard = null;
- mDaylight = null;
- }
- }
-
- /**
- * {@inheritDoc}
- */
- public int estimateLength() {
- if (mTimeZoneForced) {
- return Math.max(mStandard.length(), mDaylight.length());
- } else if (mStyle == TimeZone.SHORT) {
- return 4;
- } else {
- return 40;
- }
- }
-
- /**
- * {@inheritDoc}
- */
- public void appendTo(StringBuffer buffer, Calendar calendar) {
- if (mTimeZoneForced) {
- if (mTimeZone.useDaylightTime() && calendar.get(Calendar.DST_OFFSET) != 0) {
- buffer.append(mDaylight);
- } else {
- buffer.append(mStandard);
- }
- } else {
- TimeZone timeZone = calendar.getTimeZone();
- if (timeZone.useDaylightTime() && calendar.get(Calendar.DST_OFFSET) != 0) {
- buffer.append(getTimeZoneDisplay(timeZone, true, mStyle, mLocale));
- } else {
- buffer.append(getTimeZoneDisplay(timeZone, false, mStyle, mLocale));
- }
- }
- }
- }
-
- /**
- * Inner class to output a time zone as a number +/-HHMM
- * or +/-HH:MM
.
TimeZoneNumberRule
with the specified properties.
- *
- * @param colon add colon between HH and MM in the output if true
- */
- TimeZoneNumberRule(boolean colon) {
- mColon = colon;
- }
-
- /**
- * {@inheritDoc}
- */
- public int estimateLength() {
- return 5;
- }
-
- /**
- * {@inheritDoc}
- */
- public void appendTo(StringBuffer buffer, Calendar calendar) {
- int offset = calendar.get(Calendar.ZONE_OFFSET) + calendar.get(Calendar.DST_OFFSET);
-
- if (offset < 0) {
- buffer.append('-');
- offset = -offset;
- } else {
- buffer.append('+');
- }
-
- int hours = offset / (60 * 60 * 1000);
- buffer.append((char)(hours / 10 + '0'));
- buffer.append((char)(hours % 10 + '0'));
-
- if (mColon) {
- buffer.append(':');
- }
-
- int minutes = offset / (60 * 1000) - 60 * hours;
- buffer.append((char)(minutes / 10 + '0'));
- buffer.append((char)(minutes % 10 + '0'));
- }
- }
-
- // ----------------------------------------------------------------------
- /**
- * Inner class that acts as a compound key for time zone names.
- */ - private static class TimeZoneDisplayKey { - private final TimeZone mTimeZone; - private final int mStyle; - private final Locale mLocale; - - /** - * Constructs an instance ofTimeZoneDisplayKey
with the specified properties.
- *
- * @param timeZone the time zone
- * @param daylight adjust the style for daylight saving time if true
- * @param style the timezone style
- * @param locale the timezone locale
- */
- TimeZoneDisplayKey(TimeZone timeZone,
- boolean daylight, int style, Locale locale) {
- mTimeZone = timeZone;
- if (daylight) {
- style |= 0x80000000;
- }
- mStyle = style;
- mLocale = locale;
- }
-
- /**
- * {@inheritDoc}
- */
- public int hashCode() {
- return mStyle * 31 + mLocale.hashCode();
- }
-
- /**
- * {@inheritDoc}
- */
- public boolean equals(Object obj) {
- if (this == obj) {
- return true;
- }
- if (obj instanceof TimeZoneDisplayKey) {
- TimeZoneDisplayKey other = (TimeZoneDisplayKey)obj;
- return
- mTimeZone.equals(other.mTimeZone) &&
- mStyle == other.mStyle &&
- mLocale.equals(other.mLocale);
- }
- return false;
- }
- }
-
- // ----------------------------------------------------------------------
- /**
- * Helper class for creating compound objects.
- * - *One use for this class is to create a hashtable key - * out of multiple objects.
- */ - private static class Pair { - private final Object mObj1; - private final Object mObj2; - - /** - * Constructs an instance ofPair
to hold the specified objects.
- * @param obj1 one object in the pair
- * @param obj2 second object in the pair
- */
- public Pair(Object obj1, Object obj2) {
- mObj1 = obj1;
- mObj2 = obj2;
- }
-
- /**
- * {@inheritDoc}
- */
- public boolean equals(Object obj) {
- if (this == obj) {
- return true;
- }
-
- if (!(obj instanceof Pair)) {
- return false;
- }
-
- Pair key = (Pair)obj;
-
- return
- (mObj1 == null ?
- key.mObj1 == null : mObj1.equals(key.mObj1)) &&
- (mObj2 == null ?
- key.mObj2 == null : mObj2.equals(key.mObj2));
- }
-
- /**
- * {@inheritDoc}
- */
- public int hashCode() {
- return
- (mObj1 == null ? 0 : mObj1.hashCode()) +
- (mObj2 == null ? 0 : mObj2.hashCode());
- }
-
- /**
- * {@inheritDoc}
- */
- public String toString() {
- return "[" + mObj1 + ':' + mObj2 + ']';
- }
- }
-
-}
diff --git a/TMessagesProj/src/main/java/org/telegram/android/LocaleController.java b/TMessagesProj/src/main/java/org/telegram/android/LocaleController.java
index 06a4cb05..fb20c948 100644
--- a/TMessagesProj/src/main/java/org/telegram/android/LocaleController.java
+++ b/TMessagesProj/src/main/java/org/telegram/android/LocaleController.java
@@ -18,6 +18,7 @@ import android.content.res.Configuration;
import android.text.format.DateFormat;
import android.util.Xml;
+import org.telegram.android.time.FastDateFormat;
import org.telegram.messenger.ConnectionsManager;
import org.telegram.messenger.FileLog;
import org.telegram.messenger.R;
diff --git a/TMessagesProj/src/main/java/org/telegram/android/MessagesController.java b/TMessagesProj/src/main/java/org/telegram/android/MessagesController.java
index dff83aff..06806b77 100644
--- a/TMessagesProj/src/main/java/org/telegram/android/MessagesController.java
+++ b/TMessagesProj/src/main/java/org/telegram/android/MessagesController.java
@@ -3886,8 +3886,13 @@ public class MessagesController implements NotificationCenter.NotificationCenter
return null;
}
if (chat.seq_in != layer.out_seq_no && chat.seq_in != layer.out_seq_no - 2) {
- /*TLRPC.Message decryptedMessage = processDecryptedObject(chat, message, layer.message);
- if (decryptedMessage == null) {
+ ArrayListDateParser is the "missing" interface for the parsing methods of + * {@link java.text.DateFormat}.
+ * + * @since 3.2 + */ +public interface DateParser { + + /** + * Equivalent to DateFormat.parse(String). + * + * See {@link java.text.DateFormat#parse(String)} for more information. + * + * @param source AString
whose beginning should be parsed.
+ * @return A Date
parsed from the string
+ * @throws ParseException if the beginning of the specified string cannot be parsed.
+ */
+ Date parse(String source) throws ParseException;
+
+ /**
+ * Equivalent to DateFormat.parse(String, ParsePosition).
+ *
+ * See {@link java.text.DateFormat#parse(String, ParsePosition)} for more information.
+ *
+ * @param source A String
, part of which should be parsed.
+ * @param pos A ParsePosition
object with index and error index information
+ * as described above.
+ * @return A Date
parsed from the string. In case of error, returns null.
+ * @throws NullPointerException if text or pos is null.
+ */
+ Date parse(String source, ParsePosition pos);
+
+ // Accessors
+ //-----------------------------------------------------------------------
+
+ /**
+ * Get the pattern used by this parser.
+ * + * @return the pattern, {@link java.text.SimpleDateFormat} compatible + */ + String getPattern(); + + /** + *+ * Get the time zone used by this parser. + *
+ * + *+ * The default {@link TimeZone} used to create a {@link Date} when the {@link TimeZone} is not specified by + * the format pattern. + *
+ * + * @return the time zone + */ + TimeZone getTimeZone(); + + /** + *Get the locale used by this parser.
+ * + * @return the locale + */ + Locale getLocale(); + + /** + * Parses text from a string to produce a Date. + * + * @param source AString
whose beginning should be parsed.
+ * @return a java.util.Date
object
+ * @throws ParseException if the beginning of the specified string cannot be parsed.
+ * @see java.text.DateFormat#parseObject(String)
+ */
+ Object parseObject(String source) throws ParseException;
+
+ /**
+ * Parse a date/time string according to the given parse position.
+ *
+ * @param source A String
whose beginning should be parsed.
+ * @param pos the parse position
+ * @return a java.util.Date
object
+ * @see java.text.DateFormat#parseObject(String, ParsePosition)
+ */
+ Object parseObject(String source, ParsePosition pos);
+}
diff --git a/TMessagesProj/src/main/java/org/telegram/android/time/DatePrinter.java b/TMessagesProj/src/main/java/org/telegram/android/time/DatePrinter.java
new file mode 100644
index 00000000..549e4c1d
--- /dev/null
+++ b/TMessagesProj/src/main/java/org/telegram/android/time/DatePrinter.java
@@ -0,0 +1,126 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.telegram.android.time;
+
+import java.text.FieldPosition;
+import java.util.Calendar;
+import java.util.Date;
+import java.util.Locale;
+import java.util.TimeZone;
+
+/**
+ * DatePrinter is the "missing" interface for the format methods of + * {@link java.text.DateFormat}.
+ * + * @since 3.2 + */ +public interface DatePrinter { + + /** + *Formats a millisecond {@code long} value.
+ * + * @param millis the millisecond value to format + * @return the formatted string + * @since 2.1 + */ + String format(long millis); + + /** + *Formats a {@code Date} object using a {@code GregorianCalendar}.
+ * + * @param date the date to format + * @return the formatted string + */ + String format(Date date); + + /** + *Formats a {@code Calendar} object.
+ * + * @param calendar the calendar to format + * @return the formatted string + */ + String format(Calendar calendar); + + /** + *Formats a milliseond {@code long} value into the + * supplied {@code StringBuffer}.
+ * + * @param millis the millisecond value to format + * @param buf the buffer to format into + * @return the specified string buffer + */ + StringBuffer format(long millis, StringBuffer buf); + + /** + *Formats a {@code Date} object into the + * supplied {@code StringBuffer} using a {@code GregorianCalendar}.
+ * + * @param date the date to format + * @param buf the buffer to format into + * @return the specified string buffer + */ + StringBuffer format(Date date, StringBuffer buf); + + /** + *Formats a {@code Calendar} object into the + * supplied {@code StringBuffer}.
+ * + * @param calendar the calendar to format + * @param buf the buffer to format into + * @return the specified string buffer + */ + StringBuffer format(Calendar calendar, StringBuffer buf); + + // Accessors + //----------------------------------------------------------------------- + + /** + *Gets the pattern used by this printer.
+ * + * @return the pattern, {@link java.text.SimpleDateFormat} compatible + */ + String getPattern(); + + /** + *Gets the time zone used by this printer.
+ * + *This zone is always used for {@code Date} printing.
+ * + * @return the time zone + */ + TimeZone getTimeZone(); + + /** + *Gets the locale used by this printer.
+ * + * @return the locale + */ + Locale getLocale(); + + /** + *Formats a {@code Date}, {@code Calendar} or + * {@code Long} (milliseconds) object.
+ * + * See {@link java.text.DateFormat#format(Object, StringBuffer, FieldPosition)} + * + * @param obj the object to format + * @param toAppendTo the buffer to append to + * @param pos the position - ignored + * @return the buffer passed in + */ + StringBuffer format(Object obj, StringBuffer toAppendTo, FieldPosition pos); +} diff --git a/TMessagesProj/src/main/java/org/telegram/android/time/FastDateFormat.java b/TMessagesProj/src/main/java/org/telegram/android/time/FastDateFormat.java new file mode 100644 index 00000000..372c5014 --- /dev/null +++ b/TMessagesProj/src/main/java/org/telegram/android/time/FastDateFormat.java @@ -0,0 +1,613 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.telegram.android.time; + +import java.text.DateFormat; +import java.text.FieldPosition; +import java.text.Format; +import java.text.ParseException; +import java.text.ParsePosition; +import java.util.Calendar; +import java.util.Date; +import java.util.Locale; +import java.util.TimeZone; + +/** + *FastDateFormat is a fast and thread-safe version of + * {@link java.text.SimpleDateFormat}.
+ * + *This class can be used as a direct replacement to + * {@code SimpleDateFormat} in most formatting and parsing situations. + * This class is especially useful in multi-threaded server environments. + * {@code SimpleDateFormat} is not thread-safe in any JDK version, + * nor will it be as Sun have closed the bug/RFE. + *
+ * + *All patterns are compatible with + * SimpleDateFormat (except time zones and some year patterns - see below).
+ * + *Since 3.2, FastDateFormat supports parsing as well as printing.
+ * + *Java 1.4 introduced a new pattern letter, {@code 'Z'}, to represent + * time zones in RFC822 format (eg. {@code +0800} or {@code -1100}). + * This pattern letter can be used here (on all JDK versions).
+ * + *In addition, the pattern {@code 'ZZ'} has been made to represent + * ISO8601 full format time zones (eg. {@code +08:00} or {@code -11:00}). + * This introduces a minor incompatibility with Java 1.4, but at a gain of + * useful functionality.
+ * + *Javadoc cites for the year pattern: For formatting, if the number of + * pattern letters is 2, the year is truncated to 2 digits; otherwise it is + * interpreted as a number. Starting with Java 1.7 a pattern of 'Y' or + * 'YYY' will be formatted as '2003', while it was '03' in former Java + * versions. FastDateFormat implements the behavior of Java 7.
+ * + * @since 2.0 + * @version $Id: FastDateFormat.java 1572877 2014-02-28 08:42:25Z britter $ + */ +public class FastDateFormat extends Format implements DateParser, DatePrinter { + /** + * Required for serialization support. + * + * @see java.io.Serializable + */ + private static final long serialVersionUID = 2L; + + /** + * FULL locale dependent date or time style. + */ + public static final int FULL = DateFormat.FULL; + /** + * LONG locale dependent date or time style. + */ + public static final int LONG = DateFormat.LONG; + /** + * MEDIUM locale dependent date or time style. + */ + public static final int MEDIUM = DateFormat.MEDIUM; + /** + * SHORT locale dependent date or time style. + */ + public static final int SHORT = DateFormat.SHORT; + + private static final FormatCacheGets a formatter instance using the default pattern in the + * default locale.
+ * + * @return a date/time formatter + */ + public static FastDateFormat getInstance() { + return cache.getInstance(); + } + + /** + *Gets a formatter instance using the specified pattern in the + * default locale.
+ * + * @param pattern {@link java.text.SimpleDateFormat} compatible + * pattern + * @return a pattern based date/time formatter + * @throws IllegalArgumentException if pattern is invalid + */ + public static FastDateFormat getInstance(final String pattern) { + return cache.getInstance(pattern, null, null); + } + + /** + *Gets a formatter instance using the specified pattern and + * time zone.
+ * + * @param pattern {@link java.text.SimpleDateFormat} compatible + * pattern + * @param timeZone optional time zone, overrides time zone of + * formatted date + * @return a pattern based date/time formatter + * @throws IllegalArgumentException if pattern is invalid + */ + public static FastDateFormat getInstance(final String pattern, final TimeZone timeZone) { + return cache.getInstance(pattern, timeZone, null); + } + + /** + *Gets a formatter instance using the specified pattern and + * locale.
+ * + * @param pattern {@link java.text.SimpleDateFormat} compatible + * pattern + * @param locale optional locale, overrides system locale + * @return a pattern based date/time formatter + * @throws IllegalArgumentException if pattern is invalid + */ + public static FastDateFormat getInstance(final String pattern, final Locale locale) { + return cache.getInstance(pattern, null, locale); + } + + /** + *Gets a formatter instance using the specified pattern, time zone + * and locale.
+ * + * @param pattern {@link java.text.SimpleDateFormat} compatible + * pattern + * @param timeZone optional time zone, overrides time zone of + * formatted date + * @param locale optional locale, overrides system locale + * @return a pattern based date/time formatter + * @throws IllegalArgumentException if pattern is invalid + * or {@code null} + */ + public static FastDateFormat getInstance(final String pattern, final TimeZone timeZone, final Locale locale) { + return cache.getInstance(pattern, timeZone, locale); + } + + //----------------------------------------------------------------------- + + /** + *Gets a date formatter instance using the specified style in the + * default time zone and locale.
+ * + * @param style date style: FULL, LONG, MEDIUM, or SHORT + * @return a localized standard date formatter + * @throws IllegalArgumentException if the Locale has no date + * pattern defined + * @since 2.1 + */ + public static FastDateFormat getDateInstance(final int style) { + return cache.getDateInstance(style, null, null); + } + + /** + *Gets a date formatter instance using the specified style and + * locale in the default time zone.
+ * + * @param style date style: FULL, LONG, MEDIUM, or SHORT + * @param locale optional locale, overrides system locale + * @return a localized standard date formatter + * @throws IllegalArgumentException if the Locale has no date + * pattern defined + * @since 2.1 + */ + public static FastDateFormat getDateInstance(final int style, final Locale locale) { + return cache.getDateInstance(style, null, locale); + } + + /** + *Gets a date formatter instance using the specified style and + * time zone in the default locale.
+ * + * @param style date style: FULL, LONG, MEDIUM, or SHORT + * @param timeZone optional time zone, overrides time zone of + * formatted date + * @return a localized standard date formatter + * @throws IllegalArgumentException if the Locale has no date + * pattern defined + * @since 2.1 + */ + public static FastDateFormat getDateInstance(final int style, final TimeZone timeZone) { + return cache.getDateInstance(style, timeZone, null); + } + + /** + *Gets a date formatter instance using the specified style, time + * zone and locale.
+ * + * @param style date style: FULL, LONG, MEDIUM, or SHORT + * @param timeZone optional time zone, overrides time zone of + * formatted date + * @param locale optional locale, overrides system locale + * @return a localized standard date formatter + * @throws IllegalArgumentException if the Locale has no date + * pattern defined + */ + public static FastDateFormat getDateInstance(final int style, final TimeZone timeZone, final Locale locale) { + return cache.getDateInstance(style, timeZone, locale); + } + + //----------------------------------------------------------------------- + + /** + *Gets a time formatter instance using the specified style in the + * default time zone and locale.
+ * + * @param style time style: FULL, LONG, MEDIUM, or SHORT + * @return a localized standard time formatter + * @throws IllegalArgumentException if the Locale has no time + * pattern defined + * @since 2.1 + */ + public static FastDateFormat getTimeInstance(final int style) { + return cache.getTimeInstance(style, null, null); + } + + /** + *Gets a time formatter instance using the specified style and + * locale in the default time zone.
+ * + * @param style time style: FULL, LONG, MEDIUM, or SHORT + * @param locale optional locale, overrides system locale + * @return a localized standard time formatter + * @throws IllegalArgumentException if the Locale has no time + * pattern defined + * @since 2.1 + */ + public static FastDateFormat getTimeInstance(final int style, final Locale locale) { + return cache.getTimeInstance(style, null, locale); + } + + /** + *Gets a time formatter instance using the specified style and + * time zone in the default locale.
+ * + * @param style time style: FULL, LONG, MEDIUM, or SHORT + * @param timeZone optional time zone, overrides time zone of + * formatted time + * @return a localized standard time formatter + * @throws IllegalArgumentException if the Locale has no time + * pattern defined + * @since 2.1 + */ + public static FastDateFormat getTimeInstance(final int style, final TimeZone timeZone) { + return cache.getTimeInstance(style, timeZone, null); + } + + /** + *Gets a time formatter instance using the specified style, time + * zone and locale.
+ * + * @param style time style: FULL, LONG, MEDIUM, or SHORT + * @param timeZone optional time zone, overrides time zone of + * formatted time + * @param locale optional locale, overrides system locale + * @return a localized standard time formatter + * @throws IllegalArgumentException if the Locale has no time + * pattern defined + */ + public static FastDateFormat getTimeInstance(final int style, final TimeZone timeZone, final Locale locale) { + return cache.getTimeInstance(style, timeZone, locale); + } + + //----------------------------------------------------------------------- + + /** + *Gets a date/time formatter instance using the specified style + * in the default time zone and locale.
+ * + * @param dateStyle date style: FULL, LONG, MEDIUM, or SHORT + * @param timeStyle time style: FULL, LONG, MEDIUM, or SHORT + * @return a localized standard date/time formatter + * @throws IllegalArgumentException if the Locale has no date/time + * pattern defined + * @since 2.1 + */ + public static FastDateFormat getDateTimeInstance(final int dateStyle, final int timeStyle) { + return cache.getDateTimeInstance(dateStyle, timeStyle, null, null); + } + + /** + *Gets a date/time formatter instance using the specified style and + * locale in the default time zone.
+ * + * @param dateStyle date style: FULL, LONG, MEDIUM, or SHORT + * @param timeStyle time style: FULL, LONG, MEDIUM, or SHORT + * @param locale optional locale, overrides system locale + * @return a localized standard date/time formatter + * @throws IllegalArgumentException if the Locale has no date/time + * pattern defined + * @since 2.1 + */ + public static FastDateFormat getDateTimeInstance(final int dateStyle, final int timeStyle, final Locale locale) { + return cache.getDateTimeInstance(dateStyle, timeStyle, null, locale); + } + + /** + *Gets a date/time formatter instance using the specified style and + * time zone in the default locale.
+ * + * @param dateStyle date style: FULL, LONG, MEDIUM, or SHORT + * @param timeStyle time style: FULL, LONG, MEDIUM, or SHORT + * @param timeZone optional time zone, overrides time zone of + * formatted date + * @return a localized standard date/time formatter + * @throws IllegalArgumentException if the Locale has no date/time + * pattern defined + * @since 2.1 + */ + public static FastDateFormat getDateTimeInstance(final int dateStyle, final int timeStyle, final TimeZone timeZone) { + return getDateTimeInstance(dateStyle, timeStyle, timeZone, null); + } + + /** + *Gets a date/time formatter instance using the specified style, + * time zone and locale.
+ * + * @param dateStyle date style: FULL, LONG, MEDIUM, or SHORT + * @param timeStyle time style: FULL, LONG, MEDIUM, or SHORT + * @param timeZone optional time zone, overrides time zone of + * formatted date + * @param locale optional locale, overrides system locale + * @return a localized standard date/time formatter + * @throws IllegalArgumentException if the Locale has no date/time + * pattern defined + */ + public static FastDateFormat getDateTimeInstance( + final int dateStyle, final int timeStyle, final TimeZone timeZone, final Locale locale) { + return cache.getDateTimeInstance(dateStyle, timeStyle, timeZone, locale); + } + + // Constructor + //----------------------------------------------------------------------- + + /** + *Constructs a new FastDateFormat.
+ * + * @param pattern {@link java.text.SimpleDateFormat} compatible pattern + * @param timeZone non-null time zone to use + * @param locale non-null locale to use + * @throws NullPointerException if pattern, timeZone, or locale is null. + */ + protected FastDateFormat(final String pattern, final TimeZone timeZone, final Locale locale) { + this(pattern, timeZone, locale, null); + } + + // Constructor + //----------------------------------------------------------------------- + + /** + *Constructs a new FastDateFormat.
+ * + * @param pattern {@link java.text.SimpleDateFormat} compatible pattern + * @param timeZone non-null time zone to use + * @param locale non-null locale to use + * @param centuryStart The start of the 100 year period to use as the "default century" for 2 digit year parsing. If centuryStart is null, defaults to now - 80 years + * @throws NullPointerException if pattern, timeZone, or locale is null. + */ + protected FastDateFormat(final String pattern, final TimeZone timeZone, final Locale locale, final Date centuryStart) { + printer = new FastDatePrinter(pattern, timeZone, locale); + parser = new FastDateParser(pattern, timeZone, locale, centuryStart); + } + + // Format methods + //----------------------------------------------------------------------- + + /** + *Formats a {@code Date}, {@code Calendar} or + * {@code Long} (milliseconds) object.
+ * + * @param obj the object to format + * @param toAppendTo the buffer to append to + * @param pos the position - ignored + * @return the buffer passed in + */ + @Override + public StringBuffer format(final Object obj, final StringBuffer toAppendTo, final FieldPosition pos) { + return printer.format(obj, toAppendTo, pos); + } + + /** + *Formats a millisecond {@code long} value.
+ * + * @param millis the millisecond value to format + * @return the formatted string + * @since 2.1 + */ + @Override + public String format(final long millis) { + return printer.format(millis); + } + + /** + *Formats a {@code Date} object using a {@code GregorianCalendar}.
+ * + * @param date the date to format + * @return the formatted string + */ + @Override + public String format(final Date date) { + return printer.format(date); + } + + /** + *Formats a {@code Calendar} object.
+ * + * @param calendar the calendar to format + * @return the formatted string + */ + @Override + public String format(final Calendar calendar) { + return printer.format(calendar); + } + + /** + *Formats a millisecond {@code long} value into the + * supplied {@code StringBuffer}.
+ * + * @param millis the millisecond value to format + * @param buf the buffer to format into + * @return the specified string buffer + * @since 2.1 + */ + @Override + public StringBuffer format(final long millis, final StringBuffer buf) { + return printer.format(millis, buf); + } + + /** + *Formats a {@code Date} object into the + * supplied {@code StringBuffer} using a {@code GregorianCalendar}.
+ * + * @param date the date to format + * @param buf the buffer to format into + * @return the specified string buffer + */ + @Override + public StringBuffer format(final Date date, final StringBuffer buf) { + return printer.format(date, buf); + } + + /** + *Formats a {@code Calendar} object into the + * supplied {@code StringBuffer}.
+ * + * @param calendar the calendar to format + * @param buf the buffer to format into + * @return the specified string buffer + */ + @Override + public StringBuffer format(final Calendar calendar, final StringBuffer buf) { + return printer.format(calendar, buf); + } + + // Parsing + //----------------------------------------------------------------------- + + + /* (non-Javadoc) + * @see DateParser#parse(java.lang.String) + */ + @Override + public Date parse(final String source) throws ParseException { + return parser.parse(source); + } + + /* (non-Javadoc) + * @see DateParser#parse(java.lang.String, java.text.ParsePosition) + */ + @Override + public Date parse(final String source, final ParsePosition pos) { + return parser.parse(source, pos); + } + + /* (non-Javadoc) + * @see java.text.Format#parseObject(java.lang.String, java.text.ParsePosition) + */ + @Override + public Object parseObject(final String source, final ParsePosition pos) { + return parser.parseObject(source, pos); + } + + // Accessors + //----------------------------------------------------------------------- + + /** + *Gets the pattern used by this formatter.
+ * + * @return the pattern, {@link java.text.SimpleDateFormat} compatible + */ + @Override + public String getPattern() { + return printer.getPattern(); + } + + /** + *Gets the time zone used by this formatter.
+ * + *This zone is always used for {@code Date} formatting.
+ * + * @return the time zone + */ + @Override + public TimeZone getTimeZone() { + return printer.getTimeZone(); + } + + /** + *Gets the locale used by this formatter.
+ * + * @return the locale + */ + @Override + public Locale getLocale() { + return printer.getLocale(); + } + + /** + *Gets an estimate for the maximum string length that the + * formatter will produce.
+ * + *The actual formatted length will almost always be less than or + * equal to this amount.
+ * + * @return the maximum formatted length + */ + public int getMaxLengthEstimate() { + return printer.getMaxLengthEstimate(); + } + + // Basics + //----------------------------------------------------------------------- + + /** + *Compares two objects for equality.
+ * + * @param obj the object to compare to + * @return {@code true} if equal + */ + @Override + public boolean equals(final Object obj) { + if (!(obj instanceof FastDateFormat)) { + return false; + } + final FastDateFormat other = (FastDateFormat) obj; + // no need to check parser, as it has same invariants as printer + return printer.equals(other.printer); + } + + /** + *Returns a hashcode compatible with equals.
+ * + * @return a hashcode compatible with equals + */ + @Override + public int hashCode() { + return printer.hashCode(); + } + + /** + *Gets a debugging string version of this formatter.
+ * + * @return a debugging string + */ + @Override + public String toString() { + return "FastDateFormat[" + printer.getPattern() + "," + printer.getLocale() + "," + printer.getTimeZone().getID() + "]"; + } + + + /** + *Performs the formatting by applying the rules to the + * specified calendar.
+ * + * @param calendar the calendar to format + * @param buf the buffer to format into + * @return the specified string buffer + */ + protected StringBuffer applyRules(final Calendar calendar, final StringBuffer buf) { + return printer.applyRules(calendar, buf); + } +} diff --git a/TMessagesProj/src/main/java/org/telegram/android/time/FastDateParser.java b/TMessagesProj/src/main/java/org/telegram/android/time/FastDateParser.java new file mode 100644 index 00000000..5fdbebb4 --- /dev/null +++ b/TMessagesProj/src/main/java/org/telegram/android/time/FastDateParser.java @@ -0,0 +1,840 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.telegram.android.time; + +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.Serializable; +import java.text.DateFormatSymbols; +import java.text.ParseException; +import java.text.ParsePosition; +import java.util.ArrayList; +import java.util.Calendar; +import java.util.Date; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.SortedMap; +import java.util.TimeZone; +import java.util.TreeMap; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + *FastDateParser is a fast and thread-safe version of + * {@link java.text.SimpleDateFormat}.
+ * + *This class can be used as a direct replacement for
+ * SimpleDateFormat
in most parsing situations.
+ * This class is especially useful in multi-threaded server environments.
+ * SimpleDateFormat
is not thread-safe in any JDK version,
+ * nor will it be as Sun has closed the
+ * bug/RFE.
+ *
Only parsing is supported, but all patterns are compatible with + * SimpleDateFormat.
+ * + *Timing tests indicate this class is as about as fast as SimpleDateFormat + * in single thread applications and about 25% faster in multi-thread applications.
+ * + * @version $Id: FastDateParser.java 1572877 2014-02-28 08:42:25Z britter $ + * @since 3.2 + */ +public class FastDateParser implements DateParser, Serializable { + /** + * Required for serialization support. + * + * @see java.io.Serializable + */ + private static final long serialVersionUID = 2L; + + static final Locale JAPANESE_IMPERIAL = new Locale("ja", "JP", "JP"); + + // defining fields + private final String pattern; + private final TimeZone timeZone; + private final Locale locale; + private final int century; + private final int startYear; + + // derived fields + private transient Pattern parsePattern; + private transient Strategy[] strategies; + + // dynamic fields to communicate with Strategy + private transient String currentFormatField; + private transient Strategy nextStrategy; + + /** + *Constructs a new FastDateParser.
+ * + * @param pattern non-null {@link java.text.SimpleDateFormat} compatible + * pattern + * @param timeZone non-null time zone to use + * @param locale non-null locale + */ + protected FastDateParser(final String pattern, final TimeZone timeZone, final Locale locale) { + this(pattern, timeZone, locale, null); + } + + /** + *Constructs a new FastDateParser.
+ * + * @param pattern non-null {@link java.text.SimpleDateFormat} compatible + * pattern + * @param timeZone non-null time zone to use + * @param locale non-null locale + * @param centuryStart The start of the century for 2 digit year parsing + * @since 3.3 + */ + protected FastDateParser(final String pattern, final TimeZone timeZone, final Locale locale, final Date centuryStart) { + this.pattern = pattern; + this.timeZone = timeZone; + this.locale = locale; + + final Calendar definingCalendar = Calendar.getInstance(timeZone, locale); + int centuryStartYear; + if (centuryStart != null) { + definingCalendar.setTime(centuryStart); + centuryStartYear = definingCalendar.get(Calendar.YEAR); + } else if (locale.equals(JAPANESE_IMPERIAL)) { + centuryStartYear = 0; + } else { + // from 80 years ago to 20 years from now + definingCalendar.setTime(new Date()); + centuryStartYear = definingCalendar.get(Calendar.YEAR) - 80; + } + century = centuryStartYear / 100 * 100; + startYear = centuryStartYear - century; + + init(definingCalendar); + } + + /** + * Initialize derived fields from defining fields. + * This is called from constructor and from readObject (de-serialization) + * + * @param definingCalendar the {@link java.util.Calendar} instance used to initialize this FastDateParser + */ + private void init(Calendar definingCalendar) { + + final StringBuilder regex = new StringBuilder(); + final ListCompare another object for equality with this object.
+ * + * @param obj the object to compare to + * @returntrue
if equal to this instance
+ */
+ @Override
+ public boolean equals(final Object obj) {
+ if (!(obj instanceof FastDateParser)) {
+ return false;
+ }
+ final FastDateParser other = (FastDateParser) obj;
+ return pattern.equals(other.pattern)
+ && timeZone.equals(other.timeZone)
+ && locale.equals(other.locale);
+ }
+
+ /**
+ * Return a hashcode compatible with equals.
+ * + * @return a hashcode compatible with equals + */ + @Override + public int hashCode() { + return pattern.hashCode() + 13 * (timeZone.hashCode() + 13 * locale.hashCode()); + } + + /** + *Get a string version of this formatter.
+ * + * @return a debugging string + */ + @Override + public String toString() { + return "FastDateParser[" + pattern + "," + locale + "," + timeZone.getID() + "]"; + } + + // Serializing + //----------------------------------------------------------------------- + + /** + * Create the object after serialization. This implementation reinitializes the + * transient properties. + * + * @param in ObjectInputStream from which the object is being deserialized. + * @throws IOException if there is an IO issue. + * @throws ClassNotFoundException if a class cannot be found. + */ + private void readObject(final ObjectInputStream in) throws IOException, ClassNotFoundException { + in.defaultReadObject(); + + final Calendar definingCalendar = Calendar.getInstance(timeZone, locale); + init(definingCalendar); + } + + /* (non-Javadoc) + * @see org.apache.commons.lang3.time.DateParser#parseObject(java.lang.String) + */ + @Override + public Object parseObject(final String source) throws ParseException { + return parse(source); + } + + /* (non-Javadoc) + * @see org.apache.commons.lang3.time.DateParser#parse(java.lang.String) + */ + @Override + public Date parse(final String source) throws ParseException { + final Date date = parse(source, new ParsePosition(0)); + if (date == null) { + // Add a note re supported date range + if (locale.equals(JAPANESE_IMPERIAL)) { + throw new ParseException( + "(The " + locale + " locale does not support dates before 1868 AD)\n" + + "Unparseable date: \"" + source + "\" does not match " + parsePattern.pattern(), 0); + } + throw new ParseException("Unparseable date: \"" + source + "\" does not match " + parsePattern.pattern(), 0); + } + return date; + } + + /* (non-Javadoc) + * @see org.apache.commons.lang3.time.DateParser#parseObject(java.lang.String, java.text.ParsePosition) + */ + @Override + public Object parseObject(final String source, final ParsePosition pos) { + return parse(source, pos); + } + + /* (non-Javadoc) + * @see org.apache.commons.lang3.time.DateParser#parse(java.lang.String, java.text.ParsePosition) + */ + @Override + public Date parse(final String source, final ParsePosition pos) { + final int offset = pos.getIndex(); + final Matcher matcher = parsePattern.matcher(source.substring(offset)); + if (!matcher.lookingAt()) { + return null; + } + // timing tests indicate getting new instance is 19% faster than cloning + final Calendar cal = Calendar.getInstance(timeZone, locale); + cal.clear(); + + for (int i = 0; i < strategies.length; ) { + final Strategy strategy = strategies[i++]; + strategy.setCalendar(this, cal, matcher.group(i)); + } + pos.setIndex(offset + matcher.end()); + return cal.getTime(); + } + + // Support for strategies + //----------------------------------------------------------------------- + + /** + * Escape constant fields into regular expression + * + * @param regex The destination regex + * @param value The source field + * @param unquote If true, replace two success quotes ('') with single quote (') + * @return TheStringBuilder
+ */
+ private static StringBuilder escapeRegex(final StringBuilder regex, final String value, final boolean unquote) {
+ regex.append("\\Q");
+ for (int i = 0; i < value.length(); ++i) {
+ char c = value.charAt(i);
+ switch (c) {
+ case '\'':
+ if (unquote) {
+ if (++i == value.length()) {
+ return regex;
+ }
+ c = value.charAt(i);
+ }
+ break;
+ case '\\':
+ if (++i == value.length()) {
+ break;
+ }
+ /*
+ * If we have found \E, we replace it with \E\\E\Q, i.e. we stop the quoting,
+ * quote the \ in \E, then restart the quoting.
+ *
+ * Otherwise we just output the two characters.
+ * In each case the initial \ needs to be output and the final char is done at the end
+ */
+ regex.append(c); // we always want the original \
+ c = value.charAt(i); // Is it followed by E ?
+ if (c == 'E') { // \E detected
+ regex.append("E\\\\E\\"); // see comment above
+ c = 'Q'; // appended below
+ }
+ break;
+ default:
+ break;
+ }
+ regex.append(c);
+ }
+ regex.append("\\E");
+ return regex;
+ }
+
+
+ /**
+ * Get the short and long values displayed for a field
+ *
+ * @param field The field of interest
+ * @param definingCalendar The calendar to obtain the short and long values
+ * @param locale The locale of display names
+ * @return A Map of the field key / value pairs
+ */
+ private static MapCalendar
to set
+ * @param value The parsed field to translate and set in cal
+ */
+ void setCalendar(final FastDateParser parser, final Calendar cal, final String value) {
+
+ }
+
+ /**
+ * Generate a Pattern
regular expression to the StringBuilder
+ * which will accept this field
+ *
+ * @param parser The parser calling this strategy
+ * @param regex The StringBuilder
to append to
+ * @return true, if this field will set the calendar;
+ * false, if this field is a constant value
+ */
+ abstract boolean addRegex(FastDateParser parser, StringBuilder regex);
+ }
+
+ /**
+ * A Pattern
to parse the user supplied SimpleDateFormat pattern
+ */
+ private static final Pattern formatPattern = Pattern.compile(
+ "D+|E+|F+|G+|H+|K+|M+|S+|W+|Z+|a+|d+|h+|k+|m+|s+|w+|y+|z+|''|'[^']++(''[^']*+)*+'|[^'A-Za-z]++");
+
+ /**
+ * Obtain a Strategy given a field from a SimpleDateFormat pattern
+ *
+ * @param formatField A sub-sequence of the SimpleDateFormat pattern
+ * @param definingCalendar The calendar to obtain the short and long values
+ * @return The Strategy that will handle parsing for the field
+ */
+ private Strategy getStrategy(final String formatField, final Calendar definingCalendar) {
+ switch (formatField.charAt(0)) {
+ case '\'':
+ if (formatField.length() > 2) {
+ return new CopyQuotedStrategy(formatField.substring(1, formatField.length() - 1));
+ }
+ //$FALL-THROUGH$
+ default:
+ return new CopyQuotedStrategy(formatField);
+ case 'D':
+ return DAY_OF_YEAR_STRATEGY;
+ case 'E':
+ return getLocaleSpecificStrategy(Calendar.DAY_OF_WEEK, definingCalendar);
+ case 'F':
+ return DAY_OF_WEEK_IN_MONTH_STRATEGY;
+ case 'G':
+ return getLocaleSpecificStrategy(Calendar.ERA, definingCalendar);
+ case 'H':
+ return MODULO_HOUR_OF_DAY_STRATEGY;
+ case 'K':
+ return HOUR_STRATEGY;
+ case 'M':
+ return formatField.length() >= 3 ? getLocaleSpecificStrategy(Calendar.MONTH, definingCalendar) : NUMBER_MONTH_STRATEGY;
+ case 'S':
+ return MILLISECOND_STRATEGY;
+ case 'W':
+ return WEEK_OF_MONTH_STRATEGY;
+ case 'a':
+ return getLocaleSpecificStrategy(Calendar.AM_PM, definingCalendar);
+ case 'd':
+ return DAY_OF_MONTH_STRATEGY;
+ case 'h':
+ return MODULO_HOUR_STRATEGY;
+ case 'k':
+ return HOUR_OF_DAY_STRATEGY;
+ case 'm':
+ return MINUTE_STRATEGY;
+ case 's':
+ return SECOND_STRATEGY;
+ case 'w':
+ return WEEK_OF_YEAR_STRATEGY;
+ case 'y':
+ return formatField.length() > 2 ? LITERAL_YEAR_STRATEGY : ABBREVIATED_YEAR_STRATEGY;
+ case 'Z':
+ case 'z':
+ return getLocaleSpecificStrategy(Calendar.ZONE_OFFSET, definingCalendar);
+ }
+ }
+
+ @SuppressWarnings("unchecked") // OK because we are creating an array with no entries
+ private static final ConcurrentMapFastDatePrinter is a fast and thread-safe version of + * {@link java.text.SimpleDateFormat}.
+ * + *This class can be used as a direct replacement to + * {@code SimpleDateFormat} in most formatting situations. + * This class is especially useful in multi-threaded server environments. + * {@code SimpleDateFormat} is not thread-safe in any JDK version, + * nor will it be as Sun have closed the bug/RFE. + *
+ * + *Only formatting is supported, but all patterns are compatible with + * SimpleDateFormat (except time zones and some year patterns - see below).
+ * + *Java 1.4 introduced a new pattern letter, {@code 'Z'}, to represent + * time zones in RFC822 format (eg. {@code +0800} or {@code -1100}). + * This pattern letter can be used here (on all JDK versions).
+ * + *In addition, the pattern {@code 'ZZ'} has been made to represent + * ISO8601 full format time zones (eg. {@code +08:00} or {@code -11:00}). + * This introduces a minor incompatibility with Java 1.4, but at a gain of + * useful functionality.
+ * + *Javadoc cites for the year pattern: For formatting, if the number of + * pattern letters is 2, the year is truncated to 2 digits; otherwise it is + * interpreted as a number. Starting with Java 1.7 a pattern of 'Y' or + * 'YYY' will be formatted as '2003', while it was '03' in former Java + * versions. FastDatePrinter implements the behavior of Java 7.
+ * + * @version $Id: FastDatePrinter.java 1567799 2014-02-12 23:25:58Z sebb $ + * @since 3.2 + */ +public class FastDatePrinter implements DatePrinter, Serializable { + // A lot of the speed in this class comes from caching, but some comes + // from the special int to StringBuffer conversion. + // + // The following produces a padded 2 digit number: + // buffer.append((char)(value / 10 + '0')); + // buffer.append((char)(value % 10 + '0')); + // + // Note that the fastest append to StringBuffer is a single char (used here). + // Note that Integer.toString() is not called, the conversion is simply + // taking the value and adding (mathematically) the ASCII value for '0'. + // So, don't change this code! It works and is very fast. + + /** + * Required for serialization support. + * + * @see java.io.Serializable + */ + private static final long serialVersionUID = 1L; + + /** + * FULL locale dependent date or time style. + */ + public static final int FULL = DateFormat.FULL; + /** + * LONG locale dependent date or time style. + */ + public static final int LONG = DateFormat.LONG; + /** + * MEDIUM locale dependent date or time style. + */ + public static final int MEDIUM = DateFormat.MEDIUM; + /** + * SHORT locale dependent date or time style. + */ + public static final int SHORT = DateFormat.SHORT; + + /** + * The pattern. + */ + private final String mPattern; + /** + * The time zone. + */ + private final TimeZone mTimeZone; + /** + * The locale. + */ + private final Locale mLocale; + /** + * The parsed rules. + */ + private transient Rule[] mRules; + /** + * The estimated maximum length. + */ + private transient int mMaxLengthEstimate; + + // Constructor + //----------------------------------------------------------------------- + + /** + *Constructs a new FastDatePrinter.
+ * + * @param pattern {@link java.text.SimpleDateFormat} compatible pattern + * @param timeZone non-null time zone to use + * @param locale non-null locale to use + * @throws NullPointerException if pattern, timeZone, or locale is null. + */ + protected FastDatePrinter(final String pattern, final TimeZone timeZone, final Locale locale) { + mPattern = pattern; + mTimeZone = timeZone; + mLocale = locale; + + init(); + } + + /** + *Initializes the instance for first use.
+ */ + private void init() { + final ListReturns a list of Rules given a pattern.
+ * + * @return a {@code List} of Rule objects + * @throws IllegalArgumentException if pattern is invalid + */ + protected ListPerforms the parsing of tokens.
+ * + * @param pattern the pattern + * @param indexRef index references + * @return parsed token + */ + protected String parseToken(final String pattern, final int[] indexRef) { + final StringBuilder buf = new StringBuilder(); + + int i = indexRef[0]; + final int length = pattern.length(); + + char c = pattern.charAt(i); + if (c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z') { + // Scan a run of the same character, which indicates a time + // pattern. + buf.append(c); + + while (i + 1 < length) { + final char peek = pattern.charAt(i + 1); + if (peek == c) { + buf.append(c); + i++; + } else { + break; + } + } + } else { + // This will identify token as text. + buf.append('\''); + + boolean inLiteral = false; + + for (; i < length; i++) { + c = pattern.charAt(i); + + if (c == '\'') { + if (i + 1 < length && pattern.charAt(i + 1) == '\'') { + // '' is treated as escaped ' + i++; + buf.append(c); + } else { + inLiteral = !inLiteral; + } + } else if (!inLiteral && + (c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z')) { + i--; + break; + } else { + buf.append(c); + } + } + } + + indexRef[0] = i; + return buf.toString(); + } + + /** + *Gets an appropriate rule for the padding required.
+ * + * @param field the field to get a rule for + * @param padding the padding required + * @return a new rule with the correct padding + */ + protected NumberRule selectNumberRule(final int field, final int padding) { + switch (padding) { + case 1: + return new UnpaddedNumberField(field); + case 2: + return new TwoDigitNumberField(field); + default: + return new PaddedNumberField(field, padding); + } + } + + // Format methods + //----------------------------------------------------------------------- + + /** + *Formats a {@code Date}, {@code Calendar} or + * {@code Long} (milliseconds) object.
+ * + * @param obj the object to format + * @param toAppendTo the buffer to append to + * @param pos the position - ignored + * @return the buffer passed in + */ + @Override + public StringBuffer format(final Object obj, final StringBuffer toAppendTo, final FieldPosition pos) { + if (obj instanceof Date) { + return format((Date) obj, toAppendTo); + } else if (obj instanceof Calendar) { + return format((Calendar) obj, toAppendTo); + } else if (obj instanceof Long) { + return format(((Long) obj).longValue(), toAppendTo); + } else { + throw new IllegalArgumentException("Unknown class: " + + (obj == null ? "Performs the formatting by applying the rules to the + * specified calendar.
+ * + * @param calendar the calendar to format + * @param buf the buffer to format into + * @return the specified string buffer + */ + protected StringBuffer applyRules(final Calendar calendar, final StringBuffer buf) { + for (final Rule rule : mRules) { + rule.appendTo(buf, calendar); + } + return buf; + } + + // Accessors + //----------------------------------------------------------------------- + /* (non-Javadoc) + * @see org.apache.commons.lang3.time.DatePrinter#getPattern() + */ + @Override + public String getPattern() { + return mPattern; + } + + /* (non-Javadoc) + * @see org.apache.commons.lang3.time.DatePrinter#getTimeZone() + */ + @Override + public TimeZone getTimeZone() { + return mTimeZone; + } + + /* (non-Javadoc) + * @see org.apache.commons.lang3.time.DatePrinter#getLocale() + */ + @Override + public Locale getLocale() { + return mLocale; + } + + /** + *Gets an estimate for the maximum string length that the + * formatter will produce.
+ * + *The actual formatted length will almost always be less than or + * equal to this amount.
+ * + * @return the maximum formatted length + */ + public int getMaxLengthEstimate() { + return mMaxLengthEstimate; + } + + // Basics + //----------------------------------------------------------------------- + + /** + *Compares two objects for equality.
+ * + * @param obj the object to compare to + * @return {@code true} if equal + */ + @Override + public boolean equals(final Object obj) { + if (!(obj instanceof FastDatePrinter)) { + return false; + } + final FastDatePrinter other = (FastDatePrinter) obj; + return mPattern.equals(other.mPattern) + && mTimeZone.equals(other.mTimeZone) + && mLocale.equals(other.mLocale); + } + + /** + *Returns a hashcode compatible with equals.
+ * + * @return a hashcode compatible with equals + */ + @Override + public int hashCode() { + return mPattern.hashCode() + 13 * (mTimeZone.hashCode() + 13 * mLocale.hashCode()); + } + + /** + *Gets a debugging string version of this formatter.
+ * + * @return a debugging string + */ + @Override + public String toString() { + return "FastDatePrinter[" + mPattern + "," + mLocale + "," + mTimeZone.getID() + "]"; + } + + // Serializing + //----------------------------------------------------------------------- + + /** + * Create the object after serialization. This implementation reinitializes the + * transient properties. + * + * @param in ObjectInputStream from which the object is being deserialized. + * @throws IOException if there is an IO issue. + * @throws ClassNotFoundException if a class cannot be found. + */ + private void readObject(final ObjectInputStream in) throws IOException, ClassNotFoundException { + in.defaultReadObject(); + init(); + } + + // Rules + //----------------------------------------------------------------------- + + /** + *Inner class defining a rule.
+ */ + private interface Rule { + /** + * Returns the estimated lentgh of the result. + * + * @return the estimated length + */ + int estimateLength(); + + /** + * Appends the value of the specified calendar to the output buffer based on the rule implementation. + * + * @param buffer the output buffer + * @param calendar calendar to be appended + */ + void appendTo(StringBuffer buffer, Calendar calendar); + } + + /** + *Inner class defining a numeric rule.
+ */ + private interface NumberRule extends Rule { + /** + * Appends the specified value to the output buffer based on the rule implementation. + * + * @param buffer the output buffer + * @param value the value to be appended + */ + void appendTo(StringBuffer buffer, int value); + } + + /** + *Inner class to output a constant single character.
+ */ + private static class CharacterLiteral implements Rule { + private final char mValue; + + /** + * Constructs a new instance of {@code CharacterLiteral} + * to hold the specified value. + * + * @param value the character literal + */ + CharacterLiteral(final char value) { + mValue = value; + } + + /** + * {@inheritDoc} + */ + @Override + public int estimateLength() { + return 1; + } + + /** + * {@inheritDoc} + */ + @Override + public void appendTo(final StringBuffer buffer, final Calendar calendar) { + buffer.append(mValue); + } + } + + /** + *Inner class to output a constant string.
+ */ + private static class StringLiteral implements Rule { + private final String mValue; + + /** + * Constructs a new instance of {@code StringLiteral} + * to hold the specified value. + * + * @param value the string literal + */ + StringLiteral(final String value) { + mValue = value; + } + + /** + * {@inheritDoc} + */ + @Override + public int estimateLength() { + return mValue.length(); + } + + /** + * {@inheritDoc} + */ + @Override + public void appendTo(final StringBuffer buffer, final Calendar calendar) { + buffer.append(mValue); + } + } + + /** + *Inner class to output one of a set of values.
+ */ + private static class TextField implements Rule { + private final int mField; + private final String[] mValues; + + /** + * Constructs an instance of {@code TextField} + * with the specified field and values. + * + * @param field the field + * @param values the field values + */ + TextField(final int field, final String[] values) { + mField = field; + mValues = values; + } + + /** + * {@inheritDoc} + */ + @Override + public int estimateLength() { + int max = 0; + for (int i = mValues.length; --i >= 0; ) { + final int len = mValues[i].length(); + if (len > max) { + max = len; + } + } + return max; + } + + /** + * {@inheritDoc} + */ + @Override + public void appendTo(final StringBuffer buffer, final Calendar calendar) { + buffer.append(mValues[calendar.get(mField)]); + } + } + + /** + *Inner class to output an unpadded number.
+ */ + private static class UnpaddedNumberField implements NumberRule { + private final int mField; + + /** + * Constructs an instance of {@code UnpadedNumberField} with the specified field. + * + * @param field the field + */ + UnpaddedNumberField(final int field) { + mField = field; + } + + /** + * {@inheritDoc} + */ + @Override + public int estimateLength() { + return 4; + } + + /** + * {@inheritDoc} + */ + @Override + public void appendTo(final StringBuffer buffer, final Calendar calendar) { + appendTo(buffer, calendar.get(mField)); + } + + /** + * {@inheritDoc} + */ + @Override + public final void appendTo(final StringBuffer buffer, final int value) { + if (value < 10) { + buffer.append((char) (value + '0')); + } else if (value < 100) { + buffer.append((char) (value / 10 + '0')); + buffer.append((char) (value % 10 + '0')); + } else { + buffer.append(Integer.toString(value)); + } + } + } + + /** + *Inner class to output an unpadded month.
+ */ + private static class UnpaddedMonthField implements NumberRule { + static final UnpaddedMonthField INSTANCE = new UnpaddedMonthField(); + + /** + * Constructs an instance of {@code UnpaddedMonthField}. + */ + UnpaddedMonthField() { + super(); + } + + /** + * {@inheritDoc} + */ + @Override + public int estimateLength() { + return 2; + } + + /** + * {@inheritDoc} + */ + @Override + public void appendTo(final StringBuffer buffer, final Calendar calendar) { + appendTo(buffer, calendar.get(Calendar.MONTH) + 1); + } + + /** + * {@inheritDoc} + */ + @Override + public final void appendTo(final StringBuffer buffer, final int value) { + if (value < 10) { + buffer.append((char) (value + '0')); + } else { + buffer.append((char) (value / 10 + '0')); + buffer.append((char) (value % 10 + '0')); + } + } + } + + /** + *Inner class to output a padded number.
+ */ + private static class PaddedNumberField implements NumberRule { + private final int mField; + private final int mSize; + + /** + * Constructs an instance of {@code PaddedNumberField}. + * + * @param field the field + * @param size size of the output field + */ + PaddedNumberField(final int field, final int size) { + if (size < 3) { + // Should use UnpaddedNumberField or TwoDigitNumberField. + throw new IllegalArgumentException(); + } + mField = field; + mSize = size; + } + + /** + * {@inheritDoc} + */ + @Override + public int estimateLength() { + return 4; + } + + /** + * {@inheritDoc} + */ + @Override + public void appendTo(final StringBuffer buffer, final Calendar calendar) { + appendTo(buffer, calendar.get(mField)); + } + + /** + * {@inheritDoc} + */ + @Override + public final void appendTo(final StringBuffer buffer, final int value) { + if (value < 100) { + for (int i = mSize; --i >= 2; ) { + buffer.append('0'); + } + buffer.append((char) (value / 10 + '0')); + buffer.append((char) (value % 10 + '0')); + } else { + int digits; + if (value < 1000) { + digits = 3; + } else { + digits = Integer.toString(value).length(); + } + for (int i = mSize; --i >= digits; ) { + buffer.append('0'); + } + buffer.append(Integer.toString(value)); + } + } + } + + /** + *Inner class to output a two digit number.
+ */ + private static class TwoDigitNumberField implements NumberRule { + private final int mField; + + /** + * Constructs an instance of {@code TwoDigitNumberField} with the specified field. + * + * @param field the field + */ + TwoDigitNumberField(final int field) { + mField = field; + } + + /** + * {@inheritDoc} + */ + @Override + public int estimateLength() { + return 2; + } + + /** + * {@inheritDoc} + */ + @Override + public void appendTo(final StringBuffer buffer, final Calendar calendar) { + appendTo(buffer, calendar.get(mField)); + } + + /** + * {@inheritDoc} + */ + @Override + public final void appendTo(final StringBuffer buffer, final int value) { + if (value < 100) { + buffer.append((char) (value / 10 + '0')); + buffer.append((char) (value % 10 + '0')); + } else { + buffer.append(Integer.toString(value)); + } + } + } + + /** + *Inner class to output a two digit year.
+ */ + private static class TwoDigitYearField implements NumberRule { + static final TwoDigitYearField INSTANCE = new TwoDigitYearField(); + + /** + * Constructs an instance of {@code TwoDigitYearField}. + */ + TwoDigitYearField() { + super(); + } + + /** + * {@inheritDoc} + */ + @Override + public int estimateLength() { + return 2; + } + + /** + * {@inheritDoc} + */ + @Override + public void appendTo(final StringBuffer buffer, final Calendar calendar) { + appendTo(buffer, calendar.get(Calendar.YEAR) % 100); + } + + /** + * {@inheritDoc} + */ + @Override + public final void appendTo(final StringBuffer buffer, final int value) { + buffer.append((char) (value / 10 + '0')); + buffer.append((char) (value % 10 + '0')); + } + } + + /** + *Inner class to output a two digit month.
+ */ + private static class TwoDigitMonthField implements NumberRule { + static final TwoDigitMonthField INSTANCE = new TwoDigitMonthField(); + + /** + * Constructs an instance of {@code TwoDigitMonthField}. + */ + TwoDigitMonthField() { + super(); + } + + /** + * {@inheritDoc} + */ + @Override + public int estimateLength() { + return 2; + } + + /** + * {@inheritDoc} + */ + @Override + public void appendTo(final StringBuffer buffer, final Calendar calendar) { + appendTo(buffer, calendar.get(Calendar.MONTH) + 1); + } + + /** + * {@inheritDoc} + */ + @Override + public final void appendTo(final StringBuffer buffer, final int value) { + buffer.append((char) (value / 10 + '0')); + buffer.append((char) (value % 10 + '0')); + } + } + + /** + *Inner class to output the twelve hour field.
+ */ + private static class TwelveHourField implements NumberRule { + private final NumberRule mRule; + + /** + * Constructs an instance of {@code TwelveHourField} with the specified + * {@code NumberRule}. + * + * @param rule the rule + */ + TwelveHourField(final NumberRule rule) { + mRule = rule; + } + + /** + * {@inheritDoc} + */ + @Override + public int estimateLength() { + return mRule.estimateLength(); + } + + /** + * {@inheritDoc} + */ + @Override + public void appendTo(final StringBuffer buffer, final Calendar calendar) { + int value = calendar.get(Calendar.HOUR); + if (value == 0) { + value = calendar.getLeastMaximum(Calendar.HOUR) + 1; + } + mRule.appendTo(buffer, value); + } + + /** + * {@inheritDoc} + */ + @Override + public void appendTo(final StringBuffer buffer, final int value) { + mRule.appendTo(buffer, value); + } + } + + /** + *Inner class to output the twenty four hour field.
+ */ + private static class TwentyFourHourField implements NumberRule { + private final NumberRule mRule; + + /** + * Constructs an instance of {@code TwentyFourHourField} with the specified + * {@code NumberRule}. + * + * @param rule the rule + */ + TwentyFourHourField(final NumberRule rule) { + mRule = rule; + } + + /** + * {@inheritDoc} + */ + @Override + public int estimateLength() { + return mRule.estimateLength(); + } + + /** + * {@inheritDoc} + */ + @Override + public void appendTo(final StringBuffer buffer, final Calendar calendar) { + int value = calendar.get(Calendar.HOUR_OF_DAY); + if (value == 0) { + value = calendar.getMaximum(Calendar.HOUR_OF_DAY) + 1; + } + mRule.appendTo(buffer, value); + } + + /** + * {@inheritDoc} + */ + @Override + public void appendTo(final StringBuffer buffer, final int value) { + mRule.appendTo(buffer, value); + } + } + + //----------------------------------------------------------------------- + + private static final ConcurrentMapGets the time zone display name, using a cache for performance.
+ * + * @param tz the zone to query + * @param daylight true if daylight savings + * @param style the style to use {@code TimeZone.LONG} or {@code TimeZone.SHORT} + * @param locale the locale to use + * @return the textual name of the time zone + */ + static String getTimeZoneDisplay(final TimeZone tz, final boolean daylight, final int style, final Locale locale) { + final TimeZoneDisplayKey key = new TimeZoneDisplayKey(tz, daylight, style, locale); + String value = cTimeZoneDisplayCache.get(key); + if (value == null) { + // This is a very slow call, so cache the results. + value = tz.getDisplayName(daylight, style, locale); + final String prior = cTimeZoneDisplayCache.putIfAbsent(key, value); + if (prior != null) { + value = prior; + } + } + return value; + } + + /** + *Inner class to output a time zone name.
+ */ + private static class TimeZoneNameRule implements Rule { + private final Locale mLocale; + private final int mStyle; + private final String mStandard; + private final String mDaylight; + + /** + * Constructs an instance of {@code TimeZoneNameRule} with the specified properties. + * + * @param timeZone the time zone + * @param locale the locale + * @param style the style + */ + TimeZoneNameRule(final TimeZone timeZone, final Locale locale, final int style) { + mLocale = locale; + mStyle = style; + + mStandard = getTimeZoneDisplay(timeZone, false, style, locale); + mDaylight = getTimeZoneDisplay(timeZone, true, style, locale); + } + + /** + * {@inheritDoc} + */ + @Override + public int estimateLength() { + // We have no access to the Calendar object that will be passed to + // appendTo so base estimate on the TimeZone passed to the + // constructor + return Math.max(mStandard.length(), mDaylight.length()); + } + + /** + * {@inheritDoc} + */ + @Override + public void appendTo(final StringBuffer buffer, final Calendar calendar) { + final TimeZone zone = calendar.getTimeZone(); + if (zone.useDaylightTime() + && calendar.get(Calendar.DST_OFFSET) != 0) { + buffer.append(getTimeZoneDisplay(zone, true, mStyle, mLocale)); + } else { + buffer.append(getTimeZoneDisplay(zone, false, mStyle, mLocale)); + } + } + } + + /** + *Inner class to output a time zone as a number {@code +/-HHMM} + * or {@code +/-HH:MM}.
+ */ + private static class TimeZoneNumberRule implements Rule { + static final TimeZoneNumberRule INSTANCE_COLON = new TimeZoneNumberRule(true); + static final TimeZoneNumberRule INSTANCE_NO_COLON = new TimeZoneNumberRule(false); + + final boolean mColon; + + /** + * Constructs an instance of {@code TimeZoneNumberRule} with the specified properties. + * + * @param colon add colon between HH and MM in the output if {@code true} + */ + TimeZoneNumberRule(final boolean colon) { + mColon = colon; + } + + /** + * {@inheritDoc} + */ + @Override + public int estimateLength() { + return 5; + } + + /** + * {@inheritDoc} + */ + @Override + public void appendTo(final StringBuffer buffer, final Calendar calendar) { + int offset = calendar.get(Calendar.ZONE_OFFSET) + calendar.get(Calendar.DST_OFFSET); + + if (offset < 0) { + buffer.append('-'); + offset = -offset; + } else { + buffer.append('+'); + } + + final int hours = offset / (60 * 60 * 1000); + buffer.append((char) (hours / 10 + '0')); + buffer.append((char) (hours % 10 + '0')); + + if (mColon) { + buffer.append(':'); + } + + final int minutes = offset / (60 * 1000) - 60 * hours; + buffer.append((char) (minutes / 10 + '0')); + buffer.append((char) (minutes % 10 + '0')); + } + } + + // ---------------------------------------------------------------------- + + /** + *Inner class that acts as a compound key for time zone names.
+ */ + private static class TimeZoneDisplayKey { + private final TimeZone mTimeZone; + private final int mStyle; + private final Locale mLocale; + + /** + * Constructs an instance of {@code TimeZoneDisplayKey} with the specified properties. + * + * @param timeZone the time zone + * @param daylight adjust the style for daylight saving time if {@code true} + * @param style the timezone style + * @param locale the timezone locale + */ + TimeZoneDisplayKey(final TimeZone timeZone, + final boolean daylight, final int style, final Locale locale) { + mTimeZone = timeZone; + if (daylight) { + mStyle = style | 0x80000000; + } else { + mStyle = style; + } + mLocale = locale; + } + + /** + * {@inheritDoc} + */ + @Override + public int hashCode() { + return (mStyle * 31 + mLocale.hashCode()) * 31 + mTimeZone.hashCode(); + } + + /** + * {@inheritDoc} + */ + @Override + public boolean equals(final Object obj) { + if (this == obj) { + return true; + } + if (obj instanceof TimeZoneDisplayKey) { + final TimeZoneDisplayKey other = (TimeZoneDisplayKey) obj; + return + mTimeZone.equals(other.mTimeZone) && + mStyle == other.mStyle && + mLocale.equals(other.mLocale); + } + return false; + } + } +} diff --git a/TMessagesProj/src/main/java/org/telegram/android/time/FormatCache.java b/TMessagesProj/src/main/java/org/telegram/android/time/FormatCache.java new file mode 100644 index 00000000..bd534bf0 --- /dev/null +++ b/TMessagesProj/src/main/java/org/telegram/android/time/FormatCache.java @@ -0,0 +1,265 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.telegram.android.time; + +import java.text.DateFormat; +import java.text.Format; +import java.text.SimpleDateFormat; +import java.util.Arrays; +import java.util.Locale; +import java.util.TimeZone; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; + +/** + *FormatCache is a cache and factory for {@link Format}s.
+ * + * @since 3.0 + * @version $Id: FormatCache 892161 2009-12-18 07:21:10Z $ + */ +// TODO: Before making public move from getDateTimeInstance(Integer,...) to int; or some other approach. +abstract class FormatCacheGets a formatter instance using the default pattern in the + * default timezone and locale.
+ * + * @return a date/time formatter + */ + public F getInstance() { + return getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT, TimeZone.getDefault(), Locale.getDefault()); + } + + /** + *Gets a formatter instance using the specified pattern, time zone + * and locale.
+ * + * @param pattern {@link java.text.SimpleDateFormat} compatible + * pattern, non-null + * @param timeZone the time zone, null means use the default TimeZone + * @param locale the locale, null means use the default Locale + * @return a pattern based date/time formatter + * @throws IllegalArgumentException if pattern is invalid + * ornull
+ */
+ public F getInstance(final String pattern, TimeZone timeZone, Locale locale) {
+ if (pattern == null) {
+ throw new NullPointerException("pattern must not be null");
+ }
+ if (timeZone == null) {
+ timeZone = TimeZone.getDefault();
+ }
+ if (locale == null) {
+ locale = Locale.getDefault();
+ }
+ final MultipartKey key = new MultipartKey(pattern, timeZone, locale);
+ F format = cInstanceCache.get(key);
+ if (format == null) {
+ format = createInstance(pattern, timeZone, locale);
+ final F previousValue = cInstanceCache.putIfAbsent(key, format);
+ if (previousValue != null) {
+ // another thread snuck in and did the same work
+ // we should return the instance that is in ConcurrentMap
+ format = previousValue;
+ }
+ }
+ return format;
+ }
+
+ /**
+ * Create a format instance using the specified pattern, time zone + * and locale.
+ * + * @param pattern {@link java.text.SimpleDateFormat} compatible pattern, this will not be null. + * @param timeZone time zone, this will not be null. + * @param locale locale, this will not be null. + * @return a pattern based date/time formatter + * @throws IllegalArgumentException if pattern is invalid + * ornull
+ */
+ abstract protected F createInstance(String pattern, TimeZone timeZone, Locale locale);
+
+ /**
+ * Gets a date/time formatter instance using the specified style, + * time zone and locale.
+ * + * @param dateStyle date style: FULL, LONG, MEDIUM, or SHORT, null indicates no date in format + * @param timeStyle time style: FULL, LONG, MEDIUM, or SHORT, null indicates no time in format + * @param timeZone optional time zone, overrides time zone of + * formatted date, null means use default Locale + * @param locale optional locale, overrides system locale + * @return a localized standard date/time formatter + * @throws IllegalArgumentException if the Locale has no date/time + * pattern defined + */ + // This must remain private, see LANG-884 + private F getDateTimeInstance(final Integer dateStyle, final Integer timeStyle, final TimeZone timeZone, Locale locale) { + if (locale == null) { + locale = Locale.getDefault(); + } + final String pattern = getPatternForStyle(dateStyle, timeStyle, locale); + return getInstance(pattern, timeZone, locale); + } + + /** + *Gets a date/time formatter instance using the specified style, + * time zone and locale.
+ * + * @param dateStyle date style: FULL, LONG, MEDIUM, or SHORT + * @param timeStyle time style: FULL, LONG, MEDIUM, or SHORT + * @param timeZone optional time zone, overrides time zone of + * formatted date, null means use default Locale + * @param locale optional locale, overrides system locale + * @return a localized standard date/time formatter + * @throws IllegalArgumentException if the Locale has no date/time + * pattern defined + */ + // package protected, for access from FastDateFormat; do not make public or protected + F getDateTimeInstance(final int dateStyle, final int timeStyle, final TimeZone timeZone, Locale locale) { + return getDateTimeInstance(Integer.valueOf(dateStyle), Integer.valueOf(timeStyle), timeZone, locale); + } + + /** + *Gets a date formatter instance using the specified style, + * time zone and locale.
+ * + * @param dateStyle date style: FULL, LONG, MEDIUM, or SHORT + * @param timeZone optional time zone, overrides time zone of + * formatted date, null means use default Locale + * @param locale optional locale, overrides system locale + * @return a localized standard date/time formatter + * @throws IllegalArgumentException if the Locale has no date/time + * pattern defined + */ + // package protected, for access from FastDateFormat; do not make public or protected + F getDateInstance(final int dateStyle, final TimeZone timeZone, Locale locale) { + return getDateTimeInstance(Integer.valueOf(dateStyle), null, timeZone, locale); + } + + /** + *Gets a time formatter instance using the specified style, + * time zone and locale.
+ * + * @param timeStyle time style: FULL, LONG, MEDIUM, or SHORT + * @param timeZone optional time zone, overrides time zone of + * formatted date, null means use default Locale + * @param locale optional locale, overrides system locale + * @return a localized standard date/time formatter + * @throws IllegalArgumentException if the Locale has no date/time + * pattern defined + */ + // package protected, for access from FastDateFormat; do not make public or protected + F getTimeInstance(final int timeStyle, final TimeZone timeZone, Locale locale) { + return getDateTimeInstance(null, Integer.valueOf(timeStyle), timeZone, locale); + } + + /** + *Gets a date/time format for the specified styles and locale.
+ * + * @param dateStyle date style: FULL, LONG, MEDIUM, or SHORT, null indicates no date in format + * @param timeStyle time style: FULL, LONG, MEDIUM, or SHORT, null indicates no time in format + * @param locale The non-null locale of the desired format + * @return a localized standard date/time format + * @throws IllegalArgumentException if the Locale has no date/time pattern defined + */ + // package protected, for access from test code; do not make public or protected + static String getPatternForStyle(final Integer dateStyle, final Integer timeStyle, final Locale locale) { + final MultipartKey key = new MultipartKey(dateStyle, timeStyle, locale); + + String pattern = cDateTimeInstanceCache.get(key); + if (pattern == null) { + try { + DateFormat formatter; + if (dateStyle == null) { + formatter = DateFormat.getTimeInstance(timeStyle.intValue(), locale); + } else if (timeStyle == null) { + formatter = DateFormat.getDateInstance(dateStyle.intValue(), locale); + } else { + formatter = DateFormat.getDateTimeInstance(dateStyle.intValue(), timeStyle.intValue(), locale); + } + pattern = ((SimpleDateFormat) formatter).toPattern(); + final String previous = cDateTimeInstanceCache.putIfAbsent(key, pattern); + if (previous != null) { + // even though it doesn't matter if another thread put the pattern + // it's still good practice to return the String instance that is + // actually in the ConcurrentMap + pattern = previous; + } + } catch (final ClassCastException ex) { + throw new IllegalArgumentException("No date time pattern for locale: " + locale); + } + } + return pattern; + } + + // ---------------------------------------------------------------------- + + /** + *Helper class to hold multi-part Map keys
+ */ + private static class MultipartKey { + private final Object[] keys; + private int hashCode; + + /** + * Constructs an instance ofMultipartKey
to hold the specified objects.
+ *
+ * @param keys the set of objects that make up the key. Each key may be null.
+ */
+ public MultipartKey(final Object... keys) {
+ this.keys = keys;
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public boolean equals(final Object obj) {
+ // Eliminate the usual boilerplate because
+ // this inner static class is only used in a generic ConcurrentHashMap
+ // which will not compare against other Object types
+ return Arrays.equals(keys, ((MultipartKey) obj).keys);
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public int hashCode() {
+ if (hashCode == 0) {
+ int rc = 0;
+ for (final Object key : keys) {
+ if (key != null) {
+ rc = rc * 7 + key.hashCode();
+ }
+ }
+ hashCode = rc;
+ }
+ return hashCode;
+ }
+ }
+}
diff --git a/TMessagesProj/src/main/java/org/telegram/messenger/FileLog.java b/TMessagesProj/src/main/java/org/telegram/messenger/FileLog.java
index ab0a52c9..6ac2cbc9 100644
--- a/TMessagesProj/src/main/java/org/telegram/messenger/FileLog.java
+++ b/TMessagesProj/src/main/java/org/telegram/messenger/FileLog.java
@@ -11,7 +11,7 @@ package org.telegram.messenger;
import android.net.Uri;
import android.util.Log;
-import org.telegram.android.FastDateFormat;
+import org.telegram.android.time.FastDateFormat;
import org.telegram.ui.ApplicationLoader;
import java.io.File;
diff --git a/TMessagesProj/src/main/java/org/telegram/ui/VideoEditorActivity.java b/TMessagesProj/src/main/java/org/telegram/ui/VideoEditorActivity.java
index 18ed3fd9..b73a8b47 100644
--- a/TMessagesProj/src/main/java/org/telegram/ui/VideoEditorActivity.java
+++ b/TMessagesProj/src/main/java/org/telegram/ui/VideoEditorActivity.java
@@ -89,8 +89,8 @@ public class VideoEditorActivity extends BaseFragment implements TextureView.Sur
private float videoDuration = 0;
private long startTime = 0;
private long endTime = 0;
- private int audioFramesSize = 0;
- private int videoFramesSize = 0;
+ private long audioFramesSize = 0;
+ private long videoFramesSize = 0;
private int estimatedSize = 0;
private long esimatedDuration = 0;
private long originalSize = 0;
@@ -292,7 +292,9 @@ public class VideoEditorActivity extends BaseFragment implements TextureView.Sur
name.equals("OMX.ST.VFM.H264Enc") ||
name.equals("OMX.Exynos.avc.enc") ||
name.equals("OMX.MARVELL.VIDEO.HW.CODA7542ENCODER") ||
- name.equals("OMX.MARVELL.VIDEO.H264ENCODER")) {
+ name.equals("OMX.MARVELL.VIDEO.H264ENCODER") ||
+ name.equals("OMX.k3.video.encoder.avc") || //fix this later
+ name.equals("OMX.TI.DUCATI1.VIDEO.H264E")) { //fix this later
compressVideo.setVisibility(View.GONE);
} else {
if (MediaController.selectColorFormat(codecInfo, MediaController.MIME_TYPE) == 0) {
@@ -721,8 +723,8 @@ public class VideoEditorActivity extends BaseFragment implements TextureView.Sur
for (Box box : boxes) {
TrackBox trackBox = (TrackBox)box;
- int sampleSizes = 0;
- int trackBitrate = 0;
+ long sampleSizes = 0;
+ long trackBitrate = 0;
try {
MediaBox mediaBox = trackBox.getMediaBox();
MediaHeaderBox mediaHeaderBox = mediaBox.getMediaHeaderBox();
@@ -738,7 +740,7 @@ public class VideoEditorActivity extends BaseFragment implements TextureView.Sur
TrackHeaderBox headerBox = trackBox.getTrackHeaderBox();
if (headerBox.getWidth() != 0 && headerBox.getHeight() != 0) {
trackHeaderBox = headerBox;
- bitrate = trackBitrate / 100000 * 100000;
+ bitrate = (int)(trackBitrate / 100000 * 100000);
if (bitrate > 900000) {
bitrate = 900000;
}
@@ -768,7 +770,7 @@ public class VideoEditorActivity extends BaseFragment implements TextureView.Sur
resultHeight *= scale;
if (bitrate != 0) {
bitrate *= Math.max(0.5f, scale);
- videoFramesSize = (int)(bitrate / 8 * videoDuration);
+ videoFramesSize = (long)(bitrate / 8 * videoDuration);
}
}