Search in sources :

Example 6 with ICUUncheckedIOException

use of android.icu.util.ICUUncheckedIOException in project j2objc by google.

the class CollationLoader method loadTailoring.

public static CollationTailoring loadTailoring(ULocale locale, Output<ULocale> outValidLocale) {
    // Java porting note: ICU4J getWithFallback/getStringWithFallback currently does not
    // work well when alias table is involved in a resource path, unless full path is specified.
    // For now, collation resources does not contain such data, so the code below should work fine.
    CollationTailoring root = CollationRoot.getRoot();
    String localeName = locale.getName();
    if (localeName.length() == 0 || localeName.equals("root")) {
        outValidLocale.value = ULocale.ROOT;
        return root;
    }
    UResourceBundle bundle = null;
    try {
        bundle = ICUResourceBundle.getBundleInstance(ICUData.ICU_COLLATION_BASE_NAME, locale, ICUResourceBundle.OpenType.LOCALE_ROOT);
    } catch (MissingResourceException e) {
        outValidLocale.value = ULocale.ROOT;
        return root;
    }
    ULocale validLocale = bundle.getULocale();
    // Normalize the root locale. See
    // http://bugs.icu-project.org/trac/ticket/10715
    String validLocaleName = validLocale.getName();
    if (validLocaleName.length() == 0 || validLocaleName.equals("root")) {
        validLocale = ULocale.ROOT;
    }
    outValidLocale.value = validLocale;
    // There are zero or more tailorings in the collations table.
    UResourceBundle collations;
    try {
        collations = bundle.get("collations");
        if (collations == null) {
            return root;
        }
    } catch (MissingResourceException ignored) {
        return root;
    }
    // Fetch the collation type from the locale ID and the default type from the data.
    String type = locale.getKeywordValue("collation");
    String defaultType = "standard";
    String defT = ((ICUResourceBundle) collations).findStringWithFallback("default");
    if (defT != null) {
        defaultType = defT;
    }
    if (type == null || type.equals("default")) {
        type = defaultType;
    } else {
        type = ASCII.toLowerCase(type);
    }
    // Load the collations/type tailoring, with type fallback.
    // Java porting note: typeFallback is used for setting U_USING_DEFAULT_WARNING in
    // ICU4C, but not used by ICU4J
    // boolean typeFallback = false;
    UResourceBundle data = findWithFallback(collations, type);
    if (data == null && type.length() > 6 && type.startsWith("search")) {
        // fall back from something like "searchjl" to "search"
        // typeFallback = true;
        type = "search";
        data = findWithFallback(collations, type);
    }
    if (data == null && !type.equals(defaultType)) {
        // fall back to the default type
        // typeFallback = true;
        type = defaultType;
        data = findWithFallback(collations, type);
    }
    if (data == null && !type.equals("standard")) {
        // fall back to the "standard" type
        // typeFallback = true;
        type = "standard";
        data = findWithFallback(collations, type);
    }
    if (data == null) {
        return root;
    }
    // Is this the same as the root collator? If so, then use that instead.
    ULocale actualLocale = data.getULocale();
    // http://bugs.icu-project.org/trac/ticket/10715 ICUResourceBundle(root).getULocale() != ULocale.ROOT
    // Therefore not just if (actualLocale.equals(ULocale.ROOT) && type.equals("standard")) {
    String actualLocaleName = actualLocale.getName();
    if (actualLocaleName.length() == 0 || actualLocaleName.equals("root")) {
        actualLocale = ULocale.ROOT;
        if (type.equals("standard")) {
            return root;
        }
    }
    CollationTailoring t = new CollationTailoring(root.settings);
    t.actualLocale = actualLocale;
    // deserialize
    UResourceBundle binary = data.get("%%CollationBin");
    ByteBuffer inBytes = binary.getBinary();
    try {
        CollationDataReader.read(root, inBytes, t);
    } catch (IOException e) {
        throw new ICUUncheckedIOException("Failed to load collation tailoring data for locale:" + actualLocale + " type:" + type, e);
    }
    // Try to fetch the optional rules string.
    try {
        t.setRulesResource(data.get("Sequence"));
    } catch (MissingResourceException ignored) {
    }
    // For the valid locale, suppress the default type.
    if (!type.equals(defaultType)) {
        outValidLocale.value = validLocale.setKeywordValue("collation", type);
    }
    // For the actual locale "zh" we need to suppress pinyin instead.
    if (!actualLocale.equals(validLocale)) {
        // Opening a bundle for the actual locale should always succeed.
        UResourceBundle actualBundle = UResourceBundle.getBundleInstance(ICUData.ICU_COLLATION_BASE_NAME, actualLocale);
        defT = ((ICUResourceBundle) actualBundle).findStringWithFallback("collations/default");
        if (defT != null) {
            defaultType = defT;
        }
    }
    if (!type.equals(defaultType)) {
        t.actualLocale = t.actualLocale.setKeywordValue("collation", type);
    }
    return t;
}
Also used : UResourceBundle(android.icu.util.UResourceBundle) ICUResourceBundle(android.icu.impl.ICUResourceBundle) ULocale(android.icu.util.ULocale) MissingResourceException(java.util.MissingResourceException) ICUResourceBundle(android.icu.impl.ICUResourceBundle) ICUUncheckedIOException(android.icu.util.ICUUncheckedIOException) ICUUncheckedIOException(android.icu.util.ICUUncheckedIOException) IOException(java.io.IOException) ByteBuffer(java.nio.ByteBuffer)

Example 7 with ICUUncheckedIOException

use of android.icu.util.ICUUncheckedIOException in project j2objc by google.

the class ResourceBasedPeriodFormatterDataService method get.

@Override
public PeriodFormatterData get(String localeName) {
    // remove tag info including calendar, we don't use the calendar
    int x = localeName.indexOf('@');
    if (x != -1) {
        localeName = localeName.substring(0, x);
    }
    synchronized (this) {
        if (lastLocale != null && lastLocale.equals(localeName)) {
            return lastData;
        }
        PeriodFormatterData ld = cache.get(localeName);
        if (ld == null) {
            String ln = localeName;
            while (!availableLocales.contains(ln)) {
                int ix = ln.lastIndexOf("_");
                if (ix > -1) {
                    ln = ln.substring(0, ix);
                } else if (!"test".equals(ln)) {
                    ln = "test";
                } else {
                    ln = null;
                    break;
                }
            }
            if (ln != null) {
                String name = PATH + "pfd_" + ln + ".xml";
                try {
                    InputStreamReader reader = new InputStreamReader(ICUData.getRequiredStream(getClass(), name), "UTF-8");
                    DataRecord dr = DataRecord.read(ln, new XMLRecordReader(reader));
                    reader.close();
                    if (dr != null) {
                        // debug
                        // if (false && ln.equals("ar_EG")) {
                        // OutputStreamWriter osw = new
                        // OutputStreamWriter(System.out, "UTF-8");
                        // XMLRecordWriter xrw = new
                        // XMLRecordWriter(osw);
                        // dr.write(xrw);
                        // osw.flush();
                        // }
                        ld = new PeriodFormatterData(localeName, dr);
                    }
                } catch (UnsupportedEncodingException e) {
                    throw new MissingResourceException("Unhandled encoding for resource " + name, name, "");
                } catch (IOException e) {
                    throw new ICUUncheckedIOException("Failed to close() resource " + name, e);
                }
            } else {
                throw new MissingResourceException("Duration data not found for  " + localeName, PATH, localeName);
            }
            // if (ld == null) {
            // ld = getFallbackFormatterData();
            // }
            cache.put(localeName, ld);
        }
        lastData = ld;
        lastLocale = localeName;
        return ld;
    }
}
Also used : InputStreamReader(java.io.InputStreamReader) MissingResourceException(java.util.MissingResourceException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) ICUUncheckedIOException(android.icu.util.ICUUncheckedIOException) IOException(java.io.IOException) ICUUncheckedIOException(android.icu.util.ICUUncheckedIOException)

Example 8 with ICUUncheckedIOException

use of android.icu.util.ICUUncheckedIOException in project j2objc by google.

the class UnicodeSet method appendNewPattern.

private <T extends Appendable> T appendNewPattern(T result, boolean escapeUnprintable, boolean includeStrings) {
    try {
        result.append('[');
        int count = getRangeCount();
        // be more economical.
        if (count > 1 && getRangeStart(0) == MIN_VALUE && getRangeEnd(count - 1) == MAX_VALUE) {
            // Emit the inverse
            result.append('^');
            for (int i = 1; i < count; ++i) {
                int start = getRangeEnd(i - 1) + 1;
                int end = getRangeStart(i) - 1;
                _appendToPat(result, start, escapeUnprintable);
                if (start != end) {
                    if ((start + 1) != end) {
                        result.append('-');
                    }
                    _appendToPat(result, end, escapeUnprintable);
                }
            }
        } else // Default; emit the ranges as pairs
        {
            for (int i = 0; i < count; ++i) {
                int start = getRangeStart(i);
                int end = getRangeEnd(i);
                _appendToPat(result, start, escapeUnprintable);
                if (start != end) {
                    if ((start + 1) != end) {
                        result.append('-');
                    }
                    _appendToPat(result, end, escapeUnprintable);
                }
            }
        }
        if (includeStrings && strings.size() > 0) {
            for (String s : strings) {
                result.append('{');
                _appendToPat(result, s, escapeUnprintable);
                result.append('}');
            }
        }
        result.append(']');
        return result;
    } catch (IOException e) {
        throw new ICUUncheckedIOException(e);
    }
}
Also used : ICUUncheckedIOException(android.icu.util.ICUUncheckedIOException) ICUUncheckedIOException(android.icu.util.ICUUncheckedIOException) IOException(java.io.IOException)

Example 9 with ICUUncheckedIOException

use of android.icu.util.ICUUncheckedIOException in project j2objc by google.

the class UnicodeSet method _toPattern.

/**
 * Append a string representation of this set to result.  This will be
 * a cleaned version of the string passed to applyPattern(), if there
 * is one.  Otherwise it will be generated.
 */
private <T extends Appendable> T _toPattern(T result, boolean escapeUnprintable) {
    if (pat == null) {
        return appendNewPattern(result, escapeUnprintable, true);
    }
    try {
        if (!escapeUnprintable) {
            result.append(pat);
            return result;
        }
        boolean oddNumberOfBackslashes = false;
        for (int i = 0; i < pat.length(); ) {
            int c = pat.codePointAt(i);
            i += Character.charCount(c);
            if (Utility.isUnprintable(c)) {
                // If the unprintable character is preceded by an odd
                // number of backslashes, then it has been escaped
                // and we omit the last backslash.
                Utility.escapeUnprintable(result, c);
                oddNumberOfBackslashes = false;
            } else if (!oddNumberOfBackslashes && c == '\\') {
                // Temporarily withhold an odd-numbered backslash.
                oddNumberOfBackslashes = true;
            } else {
                if (oddNumberOfBackslashes) {
                    result.append('\\');
                }
                appendCodePoint(result, c);
                oddNumberOfBackslashes = false;
            }
        }
        if (oddNumberOfBackslashes) {
            result.append('\\');
        }
        return result;
    } catch (IOException e) {
        throw new ICUUncheckedIOException(e);
    }
}
Also used : ICUUncheckedIOException(android.icu.util.ICUUncheckedIOException) ICUUncheckedIOException(android.icu.util.ICUUncheckedIOException) IOException(java.io.IOException)

Example 10 with ICUUncheckedIOException

use of android.icu.util.ICUUncheckedIOException in project j2objc by google.

the class CaseMapImpl method toTitle.

public static <A extends Appendable> A toTitle(int caseLocale, int options, BreakIterator titleIter, CharSequence src, A dest, Edits edits) {
    try {
        if (edits != null) {
            edits.reset();
        }
        /* set up local variables */
        StringContextIterator iter = new StringContextIterator(src);
        int srcLength = src.length();
        int prev = 0;
        boolean isFirstIndex = true;
        /* titlecasing loop */
        while (prev < srcLength) {
            /* find next index where to titlecase */
            int index;
            if (isFirstIndex) {
                isFirstIndex = false;
                index = titleIter.first();
            } else {
                index = titleIter.next();
            }
            if (index == BreakIterator.DONE || index > srcLength) {
                index = srcLength;
            }
            /*
                 * Unicode 4 & 5 section 3.13 Default Case Operations:
                 *
                 * R3  toTitlecase(X): Find the word boundaries based on Unicode Standard Annex
                 * #29, "Text Boundaries." Between each pair of word boundaries, find the first
                 * cased character F. If F exists, map F to default_title(F); then map each
                 * subsequent character C to default_lower(C).
                 *
                 * In this implementation, segment [prev..index[ into 3 parts:
                 * a) uncased characters (copy as-is) [prev..titleStart[
                 * b) first case letter (titlecase)         [titleStart..titleLimit[
                 * c) subsequent characters (lowercase)                 [titleLimit..index[
                 */
            if (prev < index) {
                // find and copy uncased characters [prev..titleStart[
                int titleStart = prev;
                iter.setLimit(index);
                int c = iter.nextCaseMapCP();
                if ((options & UCharacter.TITLECASE_NO_BREAK_ADJUSTMENT) == 0 && UCaseProps.NONE == UCaseProps.INSTANCE.getType(c)) {
                    // Adjust the titlecasing index (titleStart) to the next cased character.
                    while ((c = iter.nextCaseMapCP()) >= 0 && UCaseProps.NONE == UCaseProps.INSTANCE.getType(c)) {
                    }
                    // If c<0 then we have only uncased characters in [prev..index[
                    // and stopped with titleStart==titleLimit==index.
                    titleStart = iter.getCPStart();
                    appendUnchanged(src, prev, titleStart - prev, dest, options, edits);
                }
                if (titleStart < index) {
                    int titleLimit = iter.getCPLimit();
                    // titlecase c which is from [titleStart..titleLimit[
                    c = UCaseProps.INSTANCE.toFullTitle(c, iter, dest, caseLocale);
                    appendResult(c, dest, iter.getCPLength(), options, edits);
                    // Special case Dutch IJ titlecasing
                    if (titleStart + 1 < index && caseLocale == UCaseProps.LOC_DUTCH) {
                        char c1 = src.charAt(titleStart);
                        if ((c1 == 'i' || c1 == 'I')) {
                            char c2 = src.charAt(titleStart + 1);
                            if (c2 == 'j') {
                                dest.append('J');
                                if (edits != null) {
                                    edits.addReplace(1, 1);
                                }
                                c = iter.nextCaseMapCP();
                                titleLimit++;
                                assert c == c2;
                                assert titleLimit == iter.getCPLimit();
                            } else if (c2 == 'J') {
                                // Keep the capital J from getting lowercased.
                                appendUnchanged(src, titleStart + 1, 1, dest, options, edits);
                                c = iter.nextCaseMapCP();
                                titleLimit++;
                                assert c == c2;
                                assert titleLimit == iter.getCPLimit();
                            }
                        }
                    }
                    // lowercase [titleLimit..index[
                    if (titleLimit < index) {
                        if ((options & UCharacter.TITLECASE_NO_LOWERCASE) == 0) {
                            // Normal operation: Lowercase the rest of the word.
                            internalToLower(caseLocale, options, iter, dest, edits);
                        } else {
                            // Optionally just copy the rest of the word unchanged.
                            appendUnchanged(src, titleLimit, index - titleLimit, dest, options, edits);
                            iter.moveToLimit();
                        }
                    }
                }
            }
            prev = index;
        }
        return dest;
    } catch (IOException e) {
        throw new ICUUncheckedIOException(e);
    }
}
Also used : ICUUncheckedIOException(android.icu.util.ICUUncheckedIOException) ICUUncheckedIOException(android.icu.util.ICUUncheckedIOException) IOException(java.io.IOException)

Aggregations

ICUUncheckedIOException (android.icu.util.ICUUncheckedIOException)13 IOException (java.io.IOException)13 ByteBuffer (java.nio.ByteBuffer)3 MissingResourceException (java.util.MissingResourceException)2 ICUResourceBundle (android.icu.impl.ICUResourceBundle)1 Norm2AllModes (android.icu.impl.Norm2AllModes)1 ULocale (android.icu.util.ULocale)1 UResourceBundle (android.icu.util.UResourceBundle)1 FileInputStream (java.io.FileInputStream)1 InputStream (java.io.InputStream)1 InputStreamReader (java.io.InputStreamReader)1 UnsupportedEncodingException (java.io.UnsupportedEncodingException)1