Class Cosmo

java.lang.Object
com.miloun.cosmo.Cosmo

public final class Cosmo extends Object
Cosmo — application localisation for Java.

A thin, ergonomic layer over ICU (reached through ICU4J). It bundles no locale data of its own — every result comes straight from ICU. Construct once per locale and reuse.

  • Field Details

    • locale

      public final String locale
      Canonical ICU locale id, e.g. "en_AU".
    • subtags

      public final Subtags subtags
      Parsed language / script / region subtags.
    • modifiers

      public final Modifiers modifiers
      Resolved modifiers (calendar / currency / timeZone).
  • Constructor Details

    • Cosmo

      public Cosmo(String locale)
      Builds a Cosmo for the given locale with no modifier overrides.
    • Cosmo

      public Cosmo(String locale, Modifiers modifiers)
      Parameters:
      locale - BCP-47 or underscore locale id (en_AU, fa-IR, en_AU@calendar=buddhist). null/blank falls back to the JVM's default locale.
      modifiers - optional calendar, currency and timeZone overrides; null fields are derived from the locale.
  • Method Details

    • fromSubtags

      public static Cosmo fromSubtags(Subtags subtags)
      Builds a Cosmo from locale subtags, e.g. new Subtags("en", "", "AU").
    • fromSubtags

      public static Cosmo fromSubtags(Subtags subtags, Modifiers modifiers)
      Builds a Cosmo from locale subtags instead of a string.
    • fromAcceptLanguage

      public static Cosmo fromAcceptLanguage(String header)
      Builds a Cosmo from an HTTP Accept-Language header.
    • fromAcceptLanguage

      public static Cosmo fromAcceptLanguage(String header, Modifiers modifiers)
      Builds a Cosmo from an HTTP Accept-Language header, picking the best-quality tag.
    • fromAcceptLanguage

      public static Cosmo fromAcceptLanguage(String header, Collection<String> supported)
    • fromAcceptLanguage

      public static Cosmo fromAcceptLanguage(String header, Collection<String> supported, Modifiers modifiers)
      Builds a Cosmo for the supported locale that best serves an HTTP Accept-Language header, negotiated with CLDR language-distance data (see bestMatch(java.util.Collection<java.lang.String>)). Falls back to the first supported locale.
    • get

      public Object get(String bundleName, String... path)
      Read a value from an ICU resource bundle, falling back locale → language → root.
      Parameters:
      bundleName - one of the Bundle constants.
      Returns:
      a leaf String, a nested UResourceBundle, or null if the path is absent. Mirrors the PHP port's get().
    • language

      public String language()
      Localised name of this locale's own language.
    • language

      public String language(String code)
      Localised language name ("en" → "English").
    • country

      public String country()
      Localised name of this locale's own region.
    • country

      public String country(String code)
      Localised country/region name ("AU" → "Australia").
    • script

      public String script()
      Localised name of this locale's own script ("" when it has none).
    • script

      public String script(String code)
      Localised script name ("Hans" → "Simplified").

      Uses the contextual CLDR Scripts table like the PHP port and JS's Intl.DisplayNames. ICU4J only exposes that table through the deprecated getDisplayScriptInContext; every non-deprecated API returns the stand-alone variant ("Simplified Han") and would disagree with the other three ports.

    • calendar

      public String calendar(String code)
      Localised calendar name ("buddhist" → "Buddhist Calendar").
    • direction

      public String direction()
      Text direction of this locale: "rtl" or "ltr".
    • direction

      public String direction(String language)
      Text direction of a language: "rtl" or "ltr".

      Script-based (via likely-subtags maximisation), so minority RTL languages with no locale-level layout data are detected too.

    • flag

      public String flag()
      Country flag emoji for this locale's region ("" when it has none).
    • flag

      public String flag(String country)
      Country flag emoji for a region ("AU" → "🇦🇺"). Pure codepoint math.
    • currency

      public String currency()
      Localised name of the currency modifier's currency.
    • currency

      public String currency(String code)
      Localised currency name ("AUD" → "Australian Dollar").
    • currency

      public String currency(String code, boolean symbol, boolean strict)
      Localised currency name (default) or symbol.
      Parameters:
      code - ISO 4217 code; null falls back to the currency modifier.
      symbol - return the disambiguated symbol ("A$") instead of the name.
      strict - throw on an unknown code instead of echoing it back.
    • number

      public String number(double value)
      Format a number with the locale's default decimal format.
    • number

      public String number(double value, Map<String,Object> options)
      Format a number with optional portable controls — minimumIntegerDigits, minimum/maximumFractionDigits, minimum/maximumSignificantDigits, roundingMode, roundingIncrement, useGrouping. The JS-only options (signDisplay, notation, …) are accepted but ignored.
    • precision

      public String precision(double value)
      Format a number with exactly 2 fraction digits (1 → "1.00").
    • precision

      public String precision(double value, int fractionDigits)
      Format a number with exactly fractionDigits fraction digits (1 → "1.00").
    • precision

      public String precision(double value, int fractionDigits, Map<String,Object> options)
      Format a number with a fixed number of fraction digits — always exactly fractionDigits, padding with trailing zeros and rounding as needed — then apply the options bag (see number(double, Map), e.g. maximumFractionDigits to widen the band). 1 → "1.00", 1.002 → "1.00", never "1.0".
    • percentage

      public String percentage(double value)
      Format a fraction as a percentage (0.2 → "20%").
    • percentage

      public String percentage(double value, int precision)
      Format a fraction as a percentage with at most precision fraction digits.
    • percentage

      public String percentage(double value, int precision, Map<String,Object> options)
      Format a fraction as a percentage; see number(double, Map) for the options.
    • money

      public String money(double value)
      Formats a monetary value using the currency modifier (inferred from the region when the locale has one).
      Returns:
      the formatted amount, or "" when no currency is available.
    • money

      public String money(double value, String code)
      Formats a monetary value in the given ISO 4217 currency.
    • money

      public String money(double value, String code, Integer precision, boolean strict)
      Formats a monetary value.
      Parameters:
      code - ISO 4217 code; null falls back to the currency modifier.
      precision - exact fraction digits, or null for the currency's default.
      strict - throw instead of returning "" when no currency is available.
    • money

      public String money(double value, String code, Integer precision, boolean strict, Map<String,Object> options)
      Formats a monetary value; see number(double, Map) for the options.
    • symbol

      public String symbol(String name)
      Returns a localised number symbol ("decimal", "percent", …).

      Accepts any DecimalFormatSymbols name (case-insensitive; the _symbol/_separator/_sign suffixes and separators are ignored).

    • unit

      public String unit(String category, String unit, double value)
      Format a measurement with a localised unit, full width.
    • unit

      public String unit(String category, String unit, double value, String width)
      Format a measurement with a localised unit (2.19 gigabytes).
      Parameters:
      category - informational grouping (e.g. "digital"); not required by ICU.
      unit - ICU unit identifier, e.g. "gigabyte", "celsius", "mile-per-hour".
      width - full/long → wide, medium → short, short → narrow.
    • scientific

      public String scientific(double value)
      Scientific notation (12345 → "1.2345E4").
    • compact

      public String compact(double value)
      Compact notation (1200 → "1.2K").
    • compact

      public String compact(double value, String width)
      Compact notation; "full"/"long" width gives "1.2 thousand".
    • ordinal

      public String ordinal(long number)
      Ordinal text (1 → "1st"). Uses ICU RBNF.
    • spellout

      public String spellout(double number)
      Spell a number out (42 → "forty-two"). Uses ICU RBNF.
    • duration

      public String duration(double seconds)
      Format an undirected duration in seconds as the clock form ("339:17:20").
    • duration

      public String duration(double seconds, boolean withWords)
      Format an undirected duration in seconds.
      Parameters:
      withWords - spell the units out where the locale's RBNF has a %with-words ruleset. Directed ("3 days ago") form: relativeDuration(double, String).
    • duration

      public String duration(Map<String,?> parts)
      Format a multi-unit duration map with abbreviated units ("3 hr, 5 min").
    • duration

      public String duration(Map<String,?> parts, boolean withWords)
      Format a multi-unit duration ({hours: 3, minutes: 5} → "3 hours, 5 minutes" with withWords). Accepted units: years, months, weeks, days, hours, minutes, seconds, milliseconds.
    • moment

      public String moment(Date value, String dateWidth, String timeWidth)
      Format a date and/or time using the locale's conventions.
      Parameters:
      dateWidth - / timeWidth: none/short/medium/long/full.
    • moment

      public String moment(Instant value, String dateWidth, String timeWidth)
    • date

      public String date(Date value)
      Format just the date part of a moment (short width).
    • date

      public String date(Date value, String width)
      Format just the date part of a moment.
    • date

      public String date(Instant value, String width)
    • time

      public String time(Date value)
      Format just the time (clock) part of a moment (short width).
    • time

      public String time(Date value, String width)
      Format just the time (clock) part of a moment.
    • time

      public String time(Instant value, String width)
    • formatMoment

      public String formatMoment(Date value, String pattern)
      Format a moment with a raw ICU pattern ("yyyy-MM-dd").
    • formatMoment

      public String formatMoment(Date value, String pattern, String calendar)
      Format a moment with a raw ICU pattern, forcing a calendar ("gregorian", …).
    • dateRange

      public String dateRange(Date start, Date end)
      Format a moment range with medium-width dates ("Feb 2 – 5, 2020").
    • dateRange

      public String dateRange(Date start, Date end, String dateWidth, String timeWidth)
      Format a moment range; supports the documented width combinations only.
    • compare

      public int compare(String a, String b)
      Locale-aware comparison of two strings (negative / zero / positive).
    • compare

      public int compare(String a, String b, Map<String,Object> options)
      Locale-aware comparison with optional collation tailoring — numeric (boolean) and caseFirst ("upper"/"lower"/"false").
    • sort

      public List<String> sort(Collection<String> items)
      A new list sorted by the locale's collation rules.
    • sort

      public List<String> sort(Collection<String> items, Map<String,Object> options)
      A new sorted list with optional collation tailoring (see compare(String, String, Map)).
    • sort

      public <T> List<T> sort(Collection<T> items, Function<T,String> key)
      Sort a collection of arbitrary objects by a string key, using the locale's collation rules. Mirrors PHP's sort($items, $key) overload.
      Parameters:
      key - extracts the string to sort each item by.
    • sort

      public <T> List<T> sort(Collection<T> items, Function<T,String> key, Map<String,Object> options)
      Sort by key with optional collation tailoring (see compare(String, String, Map)).
    • contains

      public boolean contains(String haystack, String needle)
      Locale-aware substring test ignoring case and accents.
    • contains

      public boolean contains(String haystack, String needle, String sensitivity)
      Locale-aware substring test with an explicit sensitivity.
    • contains

      public boolean contains(String haystack, String needle, String sensitivity, Map<String,Object> options)
      Locale-aware substring test (accents/case can be ignored).
      Parameters:
      sensitivity - base (ignore case & accents), accent, case, or variant (exact).
    • splitGraphemes

      public List<String> splitGraphemes(String text)
      Split text into grapheme clusters (combining marks / emoji stay intact).
    • splitWords

      public List<String> splitWords(String text)
      Split text into words (drops whitespace/punctuation).
    • splitSentences

      public List<String> splitSentences(String text)
      Split text into sentences using the locale's boundary rules.
    • ellipsize

      public String ellipsize(String text, int maxGraphemes)
      Truncate to at most maxGraphemes graphemes on a word boundary.
    • ellipsize

      public String ellipsize(String text, int maxGraphemes, String ellipsis)
      Truncate to at most maxGraphemes graphemes with a custom ellipsis.
    • message

      public String message(String pattern, Map<String,Object> args)
      Format an ICU MessageFormat pattern with named placeholders.
    • message

      public String message(String pattern, Object... args)
      Format an ICU MessageFormat pattern with positional ({0}) placeholders.
    • pluralCategory

      public String pluralCategory(double value)
      The LDML cardinal plural category for a value (1 → "one").
    • pluralCategory

      public String pluralCategory(double value, boolean ordinal)
      The LDML plural category; ordinal uses ordinal rules (1st/2nd/3rd …).
    • join

      public String join(Collection<String> items)
      Join a list the locale's way ("A, B, and C").
    • join

      public String join(Collection<String> items, String type)
      Join a list; type is conjunction (and), disjunction (or), or unit.
    • join

      public String join(Collection<String> items, String type, String width)
      Join a list the locale's way with an explicit type and width.
    • quote

      public String quote(String text)
      Wrap text in the locale's quotation marks (“x” in en, «x» in fa).
    • relativeDuration

      public String relativeDuration(double amount, String unit)
      Directed duration, always numeric ((-3, "day") → "3 days ago").
    • relativeDuration

      public String relativeDuration(double amount, String unit, String numeric)
      Render a directed duration.
      Parameters:
      amount - signed — negative = past ("… ago"), positive = future ("in …").
      unit - second/minute/hour/day/week/month/quarter/year.
      numeric - "always" ("1 day ago") or "auto" ("yesterday" — ICU4J exposes the word forms the Python port can't reach).
    • relativeDurationBetween

      public String relativeDurationBetween(Date target)
      Directed duration between a moment and now, largest sensible unit, word forms allowed.
    • relativeDurationBetween

      public String relativeDurationBetween(Date target, Date reference)
      Directed duration between two moments ("in 5 days", "3 days ago").
    • relativeDurationBetween

      public String relativeDurationBetween(Date target, Date reference, String numeric)
      Directed duration between two moments, computed as target − reference (reference defaults to now) and rendered in the largest sensible unit.
    • numberRange

      public String numberRange(double start, double end)
      Format a numeric range ("3–5").
    • moneyRange

      public String moneyRange(double start, double end)
      Format a monetary range with the currency modifier ("" if none).
    • moneyRange

      public String moneyRange(double start, double end, String code)
      Format a monetary range ("$3.00 – $5.00"). "" if no currency.
    • addLikelySubtags

      public Cosmo addLikelySubtags()
      A new Cosmo with likely subtags added ("en" → "en_Latn_US").
    • removeLikelySubtags

      public Cosmo removeLikelySubtags()
      A new Cosmo with likely subtags removed ("en_Latn_US" → "en").
    • monthNames

      public List<String> monthNames()
      Localised month names (full width), following the active calendar.
    • monthNames

      public List<String> monthNames(String width)
      Localised month names, following the active calendar (e.g. Persian for fa_IR).
    • weekdayNames

      public List<String> weekdayNames()
      Localised weekday names (full width), Sunday first (ICU symbol order).
    • weekdayNames

      public List<String> weekdayNames(String width)
      Localised weekday names, Sunday first (ICU symbol order).
    • weekInfo

      public WeekInfo weekInfo()
      Week conventions of the locale's region: first day, minimal days, and — unlike the Python port — the weekend days, via ICU's region week data.
    • timeZoneName

      public String timeZoneName()
      Display name of the timeZone modifier (or the system zone), long style.
    • timeZoneName

      public String timeZoneName(String style)
      Display name of the timeZone modifier (or the system zone).
      Parameters:
      style - long/short/longOffset/shortOffset/ longGeneric/shortGeneric.
    • displayName

      public String displayName(String type, String code)
      Generic localised display name — one entry point over the dedicated lookups.
      Parameters:
      type - language, region, script, calendar, or currency.
    • supportedValues

      public List<String> supportedValues(String key)
      Values the runtime's ICU supports for key (e.g. all IANA time zones).

      Supported keys: timeZone, collation, numberingSystem, unit, currency, calendar. ICU4J can enumerate the last two — an enumeration PyICU lacks, so the Python port raises for them.

    • bestMatch

      public String bestMatch(Collection<String> supported)
      The supported locale that best serves this Cosmo's locale, using CLDR language-distance data — e.g. en_AU picks en-GB over en-US, and sr-Latn is served better by hr than by sr-Cyrl. Falls back to the first supported locale when nothing matches well.
      Returns:
      the matching entry exactly as it appears in supported.
    • transliterate

      public String transliterate(String text, String id)
      Run an ICU transform over the text — script conversion, romanisation, accent folding ("Any-Latin; Latin-ASCII" makes ASCII slugs).
      Parameters:
      id - a compound ICU transliterator id; see supportedValues("transliterator") for the building blocks.
    • romanize

      public String romanize(String text)
      Romanise text ("Москва" → "Moskva"); shorthand for Any-Latin.
    • confusable

      public boolean confusable(String a, String b)
      Whether two strings are visually confusable ("paypal" vs a Cyrillic "раураl") per UTS #39. Locale-independent.
    • suspicious

      public boolean suspicious(String text)
      Whether a string fails ICU's default spoof checks (mixed scripts, restriction level, invisible characters) per UTS #39.
    • indexBuckets

      public Map<String,List<String>> indexBuckets(Collection<String> names)
      Group strings under locale-correct index headers (A–Z in en, 가나다 in ko, あかさ in ja, with the right under/overflow buckets). Buckets keep the locale's label order; empty buckets are omitted; items are collated.
    • parseNumber

      public double parseNumber(String text)
      Parse a localised number ("1.234,56" in de → 1234.56).
    • parseMoney

      public com.ibm.icu.util.CurrencyAmount parseMoney(String text)
      Parse a localised monetary string ("$12.30" → 12.3 USD).
      Returns:
      an ICU CurrencyAmount: getNumber() and getCurrency().
    • parseDate

      public Date parseDate(String text)
      Parse a short-width localised date.
    • parseDate

      public Date parseDate(String text, String width)
      Parse a localised date written at the given width (short…full).
    • parseMoment

      public Date parseMoment(String text, String pattern)
      Parse a moment with a raw ICU pattern (the inverse of formatMoment(java.util.Date, java.lang.String)).
    • personName

      public String personName(Map<String,String> fields)
      Format a person's name with medium length and formal formality.
    • personName

      public String personName(Map<String,String> fields, String length, String formality)
      Locale-aware person-name formatting from CLDR person-name data: surname-first locales (ja/zh/hu), locale-correct initials and spacing, formality variants — zero hardcoded rules.

      ICU technology preview: the underlying API may shift between ICU releases; this method's own surface will stay stable.

      Parameters:
      fields - name fields — given, surname, and optionally title, given2, surname2, generation, credentials, plus locale: the locale of the name itself (e.g. "ja" so 山田/太郎 renders surname-first).
      length - short/medium/long.
      formality - formal/informal.
    • upper

      public String upper(String text)
      Locale-aware upper-casing (e.g. Turkish dotted/dotless I).
    • lower

      public String lower(String text)
      Locale-aware lower-casing.