Example usage for java.util Locale Locale

List of usage examples for java.util Locale Locale

Introduction

In this page you can find the example usage for java.util Locale Locale.

Prototype

public Locale(String language, String country) 

Source Link

Document

Construct a locale from language and country.

Usage

From source file:com.talkdesk.geo.GeoCodeResolver.java

public String getTownFromNumber(String phoneNumber) throws GeoResolverException {
    Phonenumber.PhoneNumber number = null;
    try {//  ww  w.  j a  v  a  2 s  .c o  m
        number = PhoneNumberUtil.getInstance().parseAndKeepRawInput(phoneNumber, Constants.DEFAULT_COUNTRY);
    } catch (NumberParseException e) {
        throw new GeoResolverException("Error while parsing phone number", e);
    }
    String desc = PhoneNumberOfflineGeocoder.getInstance().getDescriptionForNumber(number,
            new Locale("en", "US"));
    String country = PhoneNumberUtil.getInstance().getRegionCodeForNumber(number);
    String[] location_array = desc.split(",");
    if (location_array != null)
        return country + ":" + location_array[0];
    else
        return country;
}

From source file:de.cosmocode.palava.ipc.legacy.LegacyHttpSessionAdapter.java

@Override
public Locale getLocale() {
    touch();/*from   w  w w .j  a  va  2  s .  c o m*/
    final Object langValue = get(LANGUAGE);
    if (locale == null || !locale.getLanguage().equals(langValue)) {

        format = null;
        collator = null;

        final Object countryValue = get(COUNTRY);

        if (langValue instanceof String && StringUtils.isNotBlank(String.class.cast(langValue))) {
            if (countryValue instanceof String && StringUtils.isNotBlank(String.class.cast(countryValue))) {
                locale = new Locale(String.class.cast(langValue), String.class.cast(countryValue));
            } else {
                locale = new Locale(String.class.cast(langValue));
            }
        } else {
            throw new IllegalStateException("No language found in session");
        }
    }
    return locale;
}

From source file:cn.vlabs.duckling.vwb.VWBFilter.java

private static Locale getLocale(String lstr) {
    if (lstr == null || lstr.length() < 1) {
        return null;
    }//from  w  w w .java2s . c o m
    Locale locale = locales.get(lstr.toLowerCase());
    if (locale != null) {
        return locale;
    } else {
        StringTokenizer localeTokens = new StringTokenizer(lstr, "_");
        String lang = null;
        String country = null;
        if (localeTokens.hasMoreTokens()) {
            lang = localeTokens.nextToken();
        }
        if (localeTokens.hasMoreTokens()) {
            country = localeTokens.nextToken();
        }
        locale = new Locale(lang, country);
        Locale crtls[] = Locale.getAvailableLocales();
        for (int i = 0; i < crtls.length; i++) {
            if (crtls[i].equals(locale)) {
                locale = crtls[i];
                break;
            }
        }
        locales.put(lstr.toLowerCase(), locale);
    }
    return locale;
}

From source file:org.vietspider.content.export.ExcelExportDataDialog.java

public void export(String domainId, File file, String[] dataHeaders) {
    if (stop)/*from  w w  w  .j  a  va2  s.  c  o m*/
        return;
    WritableWorkbook workbook = null;

    try {
        WorkbookSettings ws = new WorkbookSettings();
        ws.setLocale(new Locale("en", "EN"));
        workbook = Workbook.createWorkbook(file, ws);

        export(workbook, 0, domainId, dataHeaders);

        workbook.write();
    } catch (Exception e) {
        ClientLog.getInstance().setException(null, e);
    } finally {
        try {

            if (workbook != null)
                workbook.close();
        } catch (Exception e) {
            ClientLog.getInstance().setException(null, e);
        }
    }
}

From source file:de.iew.web.controllers.MessageBundleController.java

@RequestMapping(value = "/{languageCode}-{countryCode}/{basename}")
public ModelAndView fetchBundleAction(@PathVariable(value = "languageCode") String languageCode,
        @PathVariable(value = "countryCode") String countryCode,
        @PathVariable(value = "basename") String basename) throws Exception {
    if (log.isDebugEnabled()) {
        log.debug("Lade Sprachpaket fr " + languageCode + " und " + countryCode + " fr " + basename + ".");
    }/*from  www  .  ja v a 2 s  .c o  m*/

    MessageBundleStore bundle = this.messageBundleService
            .getMessageBundle(new Locale(languageCode, countryCode), basename);

    ModelAndView mav = new ModelAndView(this.requireJSMessageBundleView);
    mav.addObject(RequireJSMessageBundleView.MB_BUNDLE, bundle);
    return mav;
}

From source file:com.opensymphony.xwork2.conversion.impl.NumberConverterTest.java

public void testStringToBigDecimalConversionWithDotsPL() throws Exception {
    // given/*from ww  w  .j  a v  a 2  s  . c om*/
    NumberConverter converter = new NumberConverter();
    Map<String, Object> context = new HashMap<>();
    context.put(ActionContext.LOCALE, new Locale("pl", "PL"));

    // when
    Object value = converter.convertValue(context, null, null, null, "1 234,4", BigDecimal.class);

    // then
    assertEquals(BigDecimal.valueOf(1234.4), value);
}

From source file:com.w20e.socrates.formatting.TestVelocityHTMLFormatter.java

public void testFormat() {

    InstanceImpl inst = new InstanceImpl();
    ModelImpl model = new ModelImpl();
    StateManager sm = new TestStateManager();

    ArrayList<Renderable> testItems = new ArrayList<Renderable>();
    ByteArrayOutputStream out = new ByteArrayOutputStream();

    try {// w  ww . j  av  a 2  s  .  com
        inst.addNode(new NodeImpl("A01", "SOME VALUE"));
        inst.addNode(new NodeImpl("A02", "SOME VALUE"));
        inst.addNode(new NodeImpl("A03"));
        inst.addNode(new NodeImpl("locale"));

        ControlImpl item = new Input("c0");
        item.setBind("A01");
        item.setLabel("Yo dude");
        item.setHint(new TranslatableImpl("Modda"));

        ControlImpl item2 = new Input("c1");
        item2.setBind("A02");
        item2.setLabel("Yo dude2");
        item2.setHint(new TranslatableImpl("Modda2"));

        ControlImpl item3 = new Checkbox("c2");
        item3.setBind("A03");
        item3.setLabel("Check me!");

        TextBlock text = new TextBlock("c2");
        text.setText("Foo! <a href='http://la.la/la/${locale}/'>lala</a>");

        testItems.add(item);
        testItems.add(item2);
        testItems.add(item3);
        testItems.add(text);

        RunnerContextImpl ctx = new RunnerContextImpl(out, this.formatter, sm, model, inst, null);
        ctx.setLocale(new Locale("en", "GB"));

        // No local options
        this.formatter.format(testItems, out, ctx);

        assertTrue(out.toString().indexOf("enable_js: true") > -1);
        assertTrue(out.toString().indexOf("disable_ajax_validation: true") > -1);

        System.out.println(out.toString());
        assertTrue(out.toString().indexOf("Yo dude") != -1);

        assertTrue(out.toString().indexOf("Foo!") != -1);

        out.reset();

        Map<String, String> opts = new HashMap<String, String>();
        opts.put("disable_ajax_validation", "false");

        ctx.setProperty("renderOptions", opts);
        ctx.setLocale(new Locale("de", "DE"));

        this.formatter.format(testItems, out, ctx);

        assertTrue(out.toString().indexOf("enable_js: true") > -1);
        assertTrue(out.toString().indexOf("disable_ajax_validation: false") > -1);

        assertTrue(out.toString().indexOf("He du!") != -1);

        //assertTrue(out.toString().indexOf("Fuu!") != -1);

    } catch (Exception e) {

        fail(e.getMessage());
    }

    try {
        this.formatter.format(testItems, null, null);
        fail("Should fail here!");
    } catch (Exception e) {
        // Whatever...
    }
}

From source file:it.eng.spagobi.tools.importexport.services.ManageImpExpAssAction.java

public void service(SourceBean request, SourceBean response) throws Exception {
    logger.debug("IN");
    try {/*from w ww.  j a  v a 2  s .  c  om*/
        freezeHttpResponse();
        httpRequest = getHttpRequest();
        httpResponse = getHttpResponse();
        reqCont = ChannelUtilities.getRequestContainer(httpRequest);
        msgBuild = MessageBuilderFactory.getMessageBuilder();
        urlBuilder = new WebUrlBuilder();

        currTheme = ThemesManager.getCurrentTheme(reqCont);
        if (currTheme == null)
            currTheme = ThemesManager.getDefaultTheme();

        String language = httpRequest.getParameter("language");
        String country = httpRequest.getParameter("country");
        try {
            locale = new Locale(language, country);
        } catch (Exception e) {
            // ignore, the defualt locale will be considered
        }
        String message = (String) request.getAttribute("MESSAGE");
        if ((message != null) && (message.equalsIgnoreCase("SAVE_ASSOCIATION_FILE"))) {
            saveAssHandler();
        } else if ((message != null) && (message.equalsIgnoreCase("GET_ASSOCIATION_FILE_LIST"))) {
            getAssListHandler(request);
        } else if ((message != null) && (message.equalsIgnoreCase("DELETE_ASSOCIATION_FILE"))) {
            deleteAssHandler(request);
        } else if ((message != null) && (message.equalsIgnoreCase("UPLOAD_ASSOCIATION_FILE"))) {
            uploadAssHandler(request);
        } else if ((message != null) && (message.equalsIgnoreCase("DOWNLOAD_ASSOCIATION_FILE"))) {
            downloadAssHandler(request);
        } else if ((message != null) && (message.equalsIgnoreCase("CHECK_IF_EXISTS"))) {
            checkIfExistsHandler(request);
        }
    } catch (Throwable t) {
        logger.error("error during service method", t);
    } finally {
        logger.debug("OUT");
    }
}

From source file:LocaleUtils.java

/**
 * <p>Converts a String to a Locale.</p>
 *
 * <p>This method takes the string format of a locale and creates the
 * locale object from it.</p>/*from  w w w  .  java 2 s.c o m*/
 *
 * <pre>
 *   LocaleUtils.toLocale("en")         = new Locale("en", "")
 *   LocaleUtils.toLocale("en_GB")      = new Locale("en", "GB")
 *   LocaleUtils.toLocale("en_GB_xxx")  = new Locale("en", "GB", "xxx")   (#)
 * </pre>
 *
 * <p>(#) The behaviour of the JDK variant constructor changed between JDK1.3 and JDK1.4.
 * In JDK1.3, the constructor upper cases the variant, in JDK1.4, it doesn't.
 * Thus, the result from getVariant() may vary depending on your JDK.</p>
 *
 * <p>This method validates the input strictly.
 * The language code must be lowercase.
 * The country code must be uppercase.
 * The separator must be an underscore.
 * The length must be correct.
 * </p>
 *
 * @param str  the locale String to convert, null returns null
 * @return a Locale, null if null input
 * @throws IllegalArgumentException if the string is an invalid format
 */
public static Locale toLocale(String str) {
    if (str == null) {
        return null;
    }
    int len = str.length();
    if (len != 2 && len != 5 && len < 7) {
        throw new IllegalArgumentException("Invalid locale format: " + str);
    }
    char ch0 = str.charAt(0);
    char ch1 = str.charAt(1);
    if (ch0 < 'a' || ch0 > 'z' || ch1 < 'a' || ch1 > 'z') {
        throw new IllegalArgumentException("Invalid locale format: " + str);
    }
    if (len == 2) {
        return new Locale(str, "");
    } else {
        if (str.charAt(2) != '_') {
            throw new IllegalArgumentException("Invalid locale format: " + str);
        }
        char ch3 = str.charAt(3);
        if (ch3 == '_') {
            return new Locale(str.substring(0, 2), "", str.substring(4));
        }
        char ch4 = str.charAt(4);
        if (ch3 < 'A' || ch3 > 'Z' || ch4 < 'A' || ch4 > 'Z') {
            throw new IllegalArgumentException("Invalid locale format: " + str);
        }
        if (len == 5) {
            return new Locale(str.substring(0, 2), str.substring(3, 5));
        } else {
            if (str.charAt(5) != '_') {
                throw new IllegalArgumentException("Invalid locale format: " + str);
            }
            return new Locale(str.substring(0, 2), str.substring(3, 5), str.substring(6));
        }
    }
}

From source file:io.github.mywarp.mywarp.bukkit.util.versionsupport.MinecraftLocaleParser.java

/**
 * Converts a String to a Locale.//from  ww w.  j  av a  2s .co  m
 *
 * <p>This method takes the string format of a locale and creates the locale object from it.</p>
 *
 * <pre>
 *   toLocaleCaseInsensitive("")           = new Locale("", "")
 *   toLocaleCaseInsensitive("en")         = new Locale("en", "")
 *   toLocaleCaseInsensitive("en_GB")      = new Locale("en", "GB")
 *   toLocaleCaseInsensitive("en_GB_xxx")  = new Locale("en", "GB", "xyz")   (#)
 * </pre>
 *
 * <p>(#) The behaviour of the JDK variant constructor changed between JDK1.3 and JDK1.4. In JDK1.3, the constructor
 * upper cases the variant, in JDK1.4, it doesn't. Thus, the result from getVariant() may vary depending on your
 * JDK.</p>
 *
 * <p>This method validates the input: The length must be correct. The separator must be an underscore. </p>
 *
 * <p>It does <b>not</b> validate whether language and country code are lower or uppercase.</p>
 *
 * @param str the locale String to convert
 * @return a Locale
 * @throws IllegalArgumentException if the string is an invalid format
 * @see Locale#forLanguageTag(String)
 */
//Note: this implementation is adapted from Apache Commons 2.6
private static Locale toLocaleCaseInsensitive(final String str) {
    checkNotNull(str);

    if (str.isEmpty()) { //JDK 8 introduced an empty locale where all fields are blank which we do not support
        throw new IllegalArgumentException("Invalid locale format: " + str);
    }
    if (str.contains("#")) { //Cannot handle Java 7 script & extensions
        throw new IllegalArgumentException("Invalid locale format: " + str);
    }
    final int len = str.length();
    if (len < 2) {
        throw new IllegalArgumentException("Invalid locale format: " + str);
    }

    //String starting with '_'
    final char ch0 = str.charAt(0);
    if (ch0 == '_') {
        if (len < 3) {
            throw new IllegalArgumentException("Invalid locale format: " + str);
        }
        final char ch1 = str.charAt(1);
        final char ch2 = str.charAt(2);
        if (!Character.isUpperCase(ch1) || !Character.isUpperCase(ch2)) {
            throw new IllegalArgumentException("Invalid locale format: " + str);
        }
        if (len == 3) {
            return new Locale(StringUtils.EMPTY, str.substring(1, 3));
        }
        if (len < 5) {
            throw new IllegalArgumentException("Invalid locale format: " + str);
        }
        if (str.charAt(3) != '_') {
            throw new IllegalArgumentException("Invalid locale format: " + str);
        }
        return new Locale(StringUtils.EMPTY, str.substring(1, 3), str.substring(4));
    }

    //String string with characters, e.g. 'en_US'
    final String[] split = str.split("_", -1);
    final int occurrences = split.length - 1;
    switch (occurrences) {
    case 0:
        if ((len == 2 || len == 3)) {
            return new Locale(str);
        }
        throw new IllegalArgumentException("Invalid locale format: " + str);

    case 1:
        if ((split[0].length() == 2 || split[0].length() == 3) && split[1].length() == 2) {
            return new Locale(split[0], split[1]);
        }
        throw new IllegalArgumentException("Invalid locale format: " + str);

    case 2:
        if ((split[0].length() == 2 || split[0].length() == 3)
                && (split[1].length() == 0 || split[1].length() == 2) && split[2].length() > 0) {
            return new Locale(split[0], split[1], split[2]);
        }

        //fallthrough
    default:
        throw new IllegalArgumentException("Invalid locale format: " + str);
    }
}