java.util.IllformedLocaleException Java Examples

The following examples show how to use java.util.IllformedLocaleException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: CandidateEntity.java    From inception with Apache License 2.0 6 votes vote down vote up
public CandidateEntity(KBHandle aHandle)
{
    handle = aHandle;
    
    if (aHandle.getKB() == null || aHandle.getKB().getDefaultLanguage() == null) {
        locale = Locale.ENGLISH;
    }
    else {
        try {
            locale = Locale.forLanguageTag(aHandle.getKB().getDefaultLanguage());
        }
        catch (IllformedLocaleException e) {
            locale = Locale.ENGLISH;
        }
    }
}
 
Example #2
Source File: DataprepLocaleContextResolver.java    From data-prep with Apache License 2.0 6 votes vote down vote up
private Locale resolveApplicationLocale(String configuredLocale) {
    Locale locale;
    if (StringUtils.isNotBlank(configuredLocale)) {
        try {
            locale = new Locale.Builder().setLanguageTag(configuredLocale).build();
            if (delegate.getSupportedLocales().contains(locale)) {
                LOGGER.debug("Setting application locale to configured {}", locale);
            } else {
                locale = DEFAULT_LOCALE;
                LOGGER.debug("Locale {} is not available. Defaulting to {}", configuredLocale,
                        delegate.getDefaultLocale());
            }
        } catch (IllformedLocaleException e) {
            locale = DEFAULT_LOCALE;
            LOGGER.warn(
                    "Error parsing configured application locale: {}. Defaulting to {}. Locale must be in the form \"en-US\" or \"fr-FR\"",
                    configuredLocale, DEFAULT_LOCALE, e);
        }
    } else {
        locale = DEFAULT_LOCALE;
        LOGGER.debug("Setting application locale to default value {}", delegate.getDefaultLocale());
    }
    LOGGER.info("Application locale set to: '{}'", locale);
    return locale;
}
 
Example #3
Source File: RequestParameterLocaleResolver.java    From components with Apache License 2.0 6 votes vote down vote up
@Override
public Locale resolveLocale(HttpServletRequest request) {
    Locale defaultLocale = Locale.getDefault();
    String language = request.getParameter(LANGUAGE_QUERY_PARAMETER_NAME);
    if (defaultLocale != null && language == null) {
        return defaultLocale;
    }

    Locale resolvedLocale;
    try {
        resolvedLocale = new Locale.Builder().setLanguageTag(language).build();
    } catch (IllformedLocaleException e) {
        resolvedLocale = Locale.getDefault();
    }
    return resolvedLocale;
}
 
Example #4
Source File: SimplePropertiesWriter.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
@SuppressForbidden(reason = "Usage of outdated locale parsing with Locale#toString() because of backwards compatibility")
private Locale getLocale(String name) {
  if (name == null) {
    return Locale.ROOT;
  }
  for (final Locale l : Locale.getAvailableLocales()) {
    if(name.equals(l.toString()) || name.equals(l.getDisplayName(Locale.ROOT))) {
      return locale;
    }
  }
  try {
    return new Locale.Builder().setLanguageTag(name).build();
  } catch (IllformedLocaleException ex) {
    throw new DataImportHandlerException(SEVERE, "Unsupported locale for PropertyWriter: " + name);
  }
}
 
Example #5
Source File: ReactAppController.java    From mojito with Apache License 2.0 5 votes vote down vote up
/**
 * Get a valid locale from the cookie value.
 *
 * @param localeCookieValue
 * @return a valid locale.
 */
String getValidLocaleFromCookie(String localeCookieValue) {

    String validLocale;

    try {
        Locale localeFromCookie = new Locale.Builder().setLanguageTag(localeCookieValue).build();
        validLocale = localeFromCookie.toLanguageTag();
    } catch (NullPointerException | IllformedLocaleException e) {
        logger.debug("Invalid localeCookieValue, fallback to en");
        validLocale = "en";
    }

    return validLocale;
}
 
Example #6
Source File: LocalesTest.java    From sis with Apache License 2.0 5 votes vote down vote up
/**
 * Tests that {@link Locales#parse(String)} throw an exception if given an invalid argument.
 */
@Test
public void testParseInvalid() {
    try {
        Locales.parse("orange_APPLE");
        fail("Shall not parse invalid locale.");
    } catch (IllformedLocaleException e) {
        final String message = e.getMessage();
        assertTrue(message, message.contains("APPLE"));
    }
}
 
Example #7
Source File: Locales.java    From sis with Apache License 2.0 5 votes vote down vote up
/**
 * Parses the given language code and optional complements (country, variant), starting at the given index.
 * All characters before {@code fromIndex} are ignored. Characters from {@code fromIndex} to the end of the
 * string are parsed as documented in the {@link #parse(String)} method. In particular, this method tries to
 * convert 3-letters codes to 2-letters code on a <cite>best effort</cite> basis.
 *
 * <div class="note"><b>Example:</b>
 * This method is useful when language codes are appended to a base property or resource name.
 * For example a dictionary may define the {@code "remarks"} property by values associated to the
 * {@code "remarks_en"} and {@code "remarks_fr"} keys, for English and French locales respectively.</div>
 *
 * @param  code  the language code, which may be followed by country code.
 * @param  fromIndex  index of the first character to parse.
 * @return the language for the given code (never {@code null}).
 * @throws IllformedLocaleException if the given code is not valid.
 *
 * @see Locale#forLanguageTag(String)
 * @see org.apache.sis.util.iso.Types#toInternationalString(Map, String)
 */
public static Locale parse(final String code, final int fromIndex) throws IllformedLocaleException {
    ArgumentChecks.ensureNonNull("code", code);
    ArgumentChecks.ensurePositive("fromIndex", fromIndex);
    int p1 = code.indexOf('_', fromIndex);
    int i  = code.indexOf('-', fromIndex);
    if (i >= 0 && (p1 < 0 || i < p1)) {
        /*
         * IETF BCP 47 language tag string. This syntax uses the '-' separator instead of '_'.
         * Note that the '_' character is illegal for the language code, but is legal for the
         * variant. Consequently we require the '-' character to appear before the first '_'.
         */
        return unique(new Locale.Builder().setLanguageTag(code).build());
    }
    /*
     * Old syntax (e.g. "en_US" or "eng; USA"). Split in (language, country, variant) components,
     * then convert the 3-letters codes to the 2-letters ones.
     */
    String language, country = "", variant = "";
    if (p1 < 0 && (p1 = code.indexOf(';', fromIndex)) < 0) {
        p1 = code.length();
    } else {
        final int s = p1 + 1;
        int p2 = code.indexOf('_', s);
        if (p2 < 0) {
            p2 = code.length();
        } else {
            variant = (String) trimWhitespaces(code, p2+1, code.length());
        }
        country = (String) trimWhitespaces(code, s, p2);
    }
    language = (String) trimWhitespaces(code, fromIndex, p1);
    language = toISO2(language, LANGUAGE);
    country  = toISO2(country,  COUNTRY);
    return unique(new Locale.Builder().setLanguage(language).setRegion(country).setVariant(variant).build());
}
 
Example #8
Source File: TmfCoalescedEventRequestTest.java    From tracecompass with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testFail() {
    final boolean[] crFlags = new boolean[4];
    TmfCoalescedEventRequest request = setupTestRequest(crFlags);
    TmfEventRequest subRequest1 = new TmfEventRequestStub(ITmfEvent.class, range1, 100, 200);
    TmfEventRequest subRequest2 = new TmfEventRequestStub(ITmfEvent.class, range1, 100, 200);
    request.addRequest(subRequest1);
    request.addRequest(subRequest2);

    request.fail(new IllformedLocaleException("Hi"));

    // Validate the coalescing request
    assertTrue("isCompleted", request.isCompleted());
    assertTrue("isFailed", request.isFailed());
    final Throwable failCause = request.getFailureCause();
    assertNotNull("Cause of failure", failCause);
    assertEquals("Cause of failure message", "Hi", failCause.getMessage());
    assertFalse("isCancelled", request.isCancelled());

    assertTrue("handleCompleted", crFlags[0]);
    assertFalse("handleSuccess", crFlags[1]);
    assertTrue("handleFailure", crFlags[2]);
    assertFalse("handleCancel", crFlags[3]);

    // Validate the first coalesced request
    assertTrue("isCompleted", subRequest1.isCompleted());
    assertTrue("isFailed", subRequest1.isFailed());
    assertFalse("isCancelled", subRequest1.isCancelled());

    // Validate the second coalesced request
    assertTrue("isCompleted", subRequest2.isCompleted());
    assertTrue("isFailed", subRequest2.isFailed());
    assertFalse("isCancelled", subRequest2.isCancelled());
}
 
Example #9
Source File: BCP47LanguageHandler.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public Literal normalizeLanguage(String literalValue, String languageTag, ValueFactory valueFactory)
		throws LiteralUtilException {
	Objects.requireNonNull(languageTag, "Language tag cannot be null");
	Objects.requireNonNull(literalValue, "Literal value cannot be null");

	try {
		return valueFactory.createLiteral(literalValue, Literals.normalizeLanguageTag(languageTag));
	} catch (IllformedLocaleException e) {
		throw new LiteralUtilException("Could not normalize BCP47 language tag", e);
	}
}
 
Example #10
Source File: BCP47LanguageHandler.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public boolean isRecognizedLanguage(String languageTag) {
	Objects.requireNonNull(languageTag, "Language tag cannot be null");

	try {
		Literals.normalizeLanguageTag(languageTag);
	} catch (IllformedLocaleException e) {
		return false;
	}

	return true;
}
 
Example #11
Source File: Literals.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Checks if the given string is a <a href="https://tools.ietf.org/html/bcp47">BCP47</a> language tag according to
 * the rules defined by the JDK in the {@link Locale} API.
 *
 * @param languageTag A language tag
 * @return <code>true</code> if the given language tag is well-formed according to the rules specified in BCP47.
 */
public static boolean isValidLanguageTag(String languageTag) {
	try {
		new Locale.Builder().setLanguageTag(languageTag);
		return true;
	} catch (IllformedLocaleException e) {
		return false;
	}
}
 
Example #12
Source File: IncludeLocalesPlugin.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
private boolean filterOutUnsupportedTags(byte[] b) {
    List<Locale> locales;
    List<String> originalTags = Arrays.asList(new String(b).split(" "));

    try {
        locales = originalTags.stream()
            .filter(tag -> !tag.isEmpty())
            .map(IncludeLocalesPlugin::tagToLocale)
            .collect(Collectors.toList());
    } catch (IllformedLocaleException ile) {
        // Seems not an available locales string literal.
        return false;
    }

    byte[] filteredBytes = filterLocales(locales).stream()
        // Make sure the filtered language tags do exist in the
        // original supported tags for compatibility codes, e.g., "iw"
        .filter(originalTags::contains)
        .collect(Collectors.joining(" "))
        .getBytes();

    if (filteredBytes.length > b.length) {
        throw new InternalError("Size of filtered locales is bigger than the original one");
    }

    System.arraycopy(filteredBytes, 0, b, 0, filteredBytes.length);
    Arrays.fill(b, filteredBytes.length, b.length, (byte)' ');
    return true;
}
 
Example #13
Source File: StringConverter.java    From sis with Apache License 2.0 4 votes vote down vote up
@Override java.util.Locale doConvert(String source) throws IllformedLocaleException {
    return Locales.parse(source);
}
 
Example #14
Source File: DateFormatEvaluator.java    From lucene-solr with Apache License 2.0 4 votes vote down vote up
@Override
public String evaluate(String expression, Context context) {
  List<Object> l = parseParams(expression, context.getVariableResolver());
  if (l.size() < 2 || l.size() > 4) {
    throw new DataImportHandlerException(SEVERE, "'formatDate()' must have two, three or four parameters ");
  }
  Object o = l.get(0);
  Object format = l.get(1);
  if (format instanceof VariableWrapper) {
    VariableWrapper wrapper = (VariableWrapper) format;
    o = wrapper.resolve();
    format = o.toString();
  }
  Locale locale = Locale.ENGLISH; // we default to ENGLISH for dates for full Java 9 compatibility
  if(l.size()>2) {
    Object localeObj = l.get(2);
    String localeStr = null;
    if (localeObj  instanceof VariableWrapper) {
      localeStr = ((VariableWrapper) localeObj).resolve().toString();
    } else {
      localeStr = localeObj.toString();
    }
    locale = availableLocales.get(localeStr);
    if (locale == null) try {
      locale = new Locale.Builder().setLanguageTag(localeStr).build();
    } catch (IllformedLocaleException ex) {
      throw new DataImportHandlerException(SEVERE, "Malformed / non-existent locale: " + localeStr, ex);
    }
  }
  TimeZone tz = TimeZone.getDefault(); // DWS TODO: is this the right default for us?  Deserves explanation if so.
  if(l.size()==4) {
    Object tzObj = l.get(3);
    String tzStr = null;
    if (tzObj  instanceof VariableWrapper) {
      tzStr = ((VariableWrapper) tzObj).resolve().toString();
    } else {
      tzStr = tzObj.toString();
    }
    if(availableTimezones.contains(tzStr)) {
      tz = TimeZone.getTimeZone(tzStr);
    } else {
      throw new DataImportHandlerException(SEVERE, "Unsupported Timezone: " + tzStr);
    }
  }
  String dateFmt = format.toString();
  SimpleDateFormat fmt = getDateFormat(dateFmt, tz, locale);
  Date date = null;
  if (o instanceof VariableWrapper) {
    date = evaluateWrapper((VariableWrapper) o, locale, tz);
  } else {
    date = evaluateString(o.toString(), locale, tz);
  }
  return fmt.format(date);
}
 
Example #15
Source File: LocaleEnhanceTest.java    From TencentKona-8 with GNU General Public License v2.0 3 votes vote down vote up
BuilderILE(String... args) {
    super(IllformedLocaleException.class);

    this.args = args;

    run();
}
 
Example #16
Source File: LocaleEnhanceTest.java    From jdk8u60 with GNU General Public License v2.0 3 votes vote down vote up
BuilderILE(String... args) {
    super(IllformedLocaleException.class);

    this.args = args;

    run();
}
 
Example #17
Source File: ValueConverter.java    From sis with Apache License 2.0 3 votes vote down vote up
/**
 * Converts the given string to a locale. The string is the language code either as the 2
 * letters or the 3 letters ISO code. It can optionally be followed by the {@code '_'}
 * character and the country code (again either as 2 or 3 letters), optionally followed
 * by {@code '_'} and the variant.
 *
 * @param  context  context (GML version, locale, <i>etc.</i>) of the (un)marshalling process.
 * @param  value    the string to convert to a locale, or {@code null}.
 * @return the converted locale, or {@code null} if the given value was null or empty, or
 *         if an exception was thrown and {@code exceptionOccured(…)} returned {@code true}.
 * @throws IllformedLocaleException if the given string can not be converted to a locale.
 *
 * @see Locales#parse(String)
 */
public Locale toLocale(final MarshalContext context, String value) throws IllformedLocaleException {
    value = trimWhitespaces(value);
    if (value != null && !value.isEmpty()) try {
        return Locales.parse(value);
    } catch (IllformedLocaleException e) {
        if (!exceptionOccured(context, value, String.class, Locale.class, e)) {
            throw e;
        }
    }
    return null;
}
 
Example #18
Source File: LocaleEnhanceTest.java    From openjdk-jdk8u with GNU General Public License v2.0 3 votes vote down vote up
BuilderILE(String... args) {
    super(IllformedLocaleException.class);

    this.args = args;

    run();
}
 
Example #19
Source File: LocaleEnhanceTest.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 3 votes vote down vote up
BuilderILE(String... args) {
    super(IllformedLocaleException.class);

    this.args = args;

    run();
}
 
Example #20
Source File: LocaleEnhanceTest.java    From jdk8u-dev-jdk with GNU General Public License v2.0 3 votes vote down vote up
BuilderILE(String... args) {
    super(IllformedLocaleException.class);

    this.args = args;

    run();
}
 
Example #21
Source File: LocaleEnhanceTest.java    From jdk8u-jdk with GNU General Public License v2.0 3 votes vote down vote up
BuilderILE(String... args) {
    super(IllformedLocaleException.class);

    this.args = args;

    run();
}
 
Example #22
Source File: LocaleEnhanceTest.java    From jdk8u_jdk with GNU General Public License v2.0 3 votes vote down vote up
BuilderILE(String... args) {
    super(IllformedLocaleException.class);

    this.args = args;

    run();
}
 
Example #23
Source File: LocaleEnhanceTest.java    From openjdk-8 with GNU General Public License v2.0 3 votes vote down vote up
BuilderILE(String... args) {
    super(IllformedLocaleException.class);

    this.args = args;

    run();
}
 
Example #24
Source File: LocaleEnhanceTest.java    From openjdk-jdk9 with GNU General Public License v2.0 3 votes vote down vote up
BuilderILE(String... args) {
    super(IllformedLocaleException.class);

    this.args = args;

    run();
}
 
Example #25
Source File: LocaleEnhanceTest.java    From dragonwell8_jdk with GNU General Public License v2.0 3 votes vote down vote up
BuilderILE(String... args) {
    super(IllformedLocaleException.class);

    this.args = args;

    run();
}
 
Example #26
Source File: LocaleEnhanceTest.java    From jdk8u-jdk with GNU General Public License v2.0 3 votes vote down vote up
BuilderILE(String... args) {
    super(IllformedLocaleException.class);

    this.args = args;

    run();
}
 
Example #27
Source File: LocaleEnhanceTest.java    From hottub with GNU General Public License v2.0 3 votes vote down vote up
BuilderILE(String... args) {
    super(IllformedLocaleException.class);

    this.args = args;

    run();
}
 
Example #28
Source File: LocaleEnhanceTest.java    From openjdk-8-source with GNU General Public License v2.0 3 votes vote down vote up
BuilderILE(String... args) {
    super(IllformedLocaleException.class);

    this.args = args;

    run();
}
 
Example #29
Source File: Locales.java    From sis with Apache License 2.0 2 votes vote down vote up
/**
 * Parses the given language code, optionally followed by country code and variant. The given string can be either
 * the 2 letters or the 3 letters ISO 639 code. It can optionally be followed by the {@code '_'} character and the
 * country code (again either as 2 or 3 letters), optionally followed by {@code '_'} and the variant.
 *
 * <p>This method can be used when the caller wants the same {@code Locale} constants no matter if the language
 * and country codes use 2 or 3 letters. This method tries to convert 3-letters codes to 2-letters code on a
 * <cite>best effort</cite> basis.</p>
 *
 * @param  code  the language code, optionally followed by country code and variant.
 * @return the language for the given code (never {@code null}).
 * @throws IllformedLocaleException if the given code is not valid.
 *
 * @see Locale#forLanguageTag(String)
 */
public static Locale parse(final String code) throws IllformedLocaleException {
    return parse(code, 0);
}
 
Example #30
Source File: Literals.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 2 votes vote down vote up
/**
 * Normalizes the given <a href="https://tools.ietf.org/html/bcp47">BCP47</a> language tag according to the rules
 * defined by the JDK in the {@link Locale} API.
 *
 * @param languageTag An unnormalized, valid, language tag
 * @return A normalized version of the given language tag
 * @throws IllformedLocaleException If the given language tag is ill-formed according to the rules specified in
 *                                  BCP47.
 */
public static String normalizeLanguageTag(String languageTag) throws IllformedLocaleException {
	return new Locale.Builder().setLanguageTag(languageTag).build().toLanguageTag().intern();
}