Example usage for java.util Locale getLanguage

List of usage examples for java.util Locale getLanguage

Introduction

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

Prototype

public String getLanguage() 

Source Link

Document

Returns the language code of this Locale.

Usage

From source file:org.openmrs.module.coreapps.fragment.controller.DiagnosesFragmentController.java

private ConceptName getPreferredName(Locale locale, Concept concept) {
    ConceptName name = concept.getPreferredName(locale);
    if (name == null
            && (StringUtils.isNotEmpty(locale.getCountry()) || StringUtils.isNotEmpty(locale.getVariant()))) {
        name = concept.getPreferredName(new Locale(locale.getLanguage()));
    }//w w w.j  a  va2  s.c  om
    if (name == null) {
        name = concept.getName(locale);
    }
    return name;

}

From source file:org.mitre.openid.connect.config.JsonMessageSource.java

/**
 * @param locale/*from   w  ww.ja v  a2s. com*/
 * @return
 */
private List<JsonObject> getLanguageMap(Locale locale) {

    if (!languageMaps.containsKey(locale)) {
        try {
            List<JsonObject> set = new ArrayList<>();
            for (String namespace : config.getLanguageNamespaces()) {
                String filename = locale.getLanguage() + File.separator + namespace + ".json";

                Resource r = getBaseDirectory().createRelative(filename);

                logger.info("No locale loaded, trying to load from " + r);

                JsonParser parser = new JsonParser();
                JsonObject obj = (JsonObject) parser.parse(new InputStreamReader(r.getInputStream(), "UTF-8"));

                set.add(obj);
            }
            languageMaps.put(locale, set);
        } catch (JsonIOException | JsonSyntaxException | IOException e) {
            logger.error("Unable to load locale", e);
        }
    }

    return languageMaps.get(locale);

}

From source file:gwtupload.server.UploadServlet.java

/**
 * Returns the localized text of a key.//from www .  j a  va2s  .c om
 */
public static String getMessage(String key, Object... pars) {
    Locale loc = getThreadLocalRequest() == null || getThreadLocalRequest().getLocale() == null
            ? new Locale("en")
            : getThreadLocalRequest().getLocale();

    ResourceBundle res = ResourceBundle.getBundle(UploadServlet.class.getName(), loc);

    String msg = res.getString(key);
    if ("zh".equals(loc.getLanguage()) && "CN".equals(loc.getCountry())) {
        msg = convertEncodingFormat(msg, "ISO-8859-1", "UTF-8");
    }
    return new MessageFormat(msg, loc).format(pars);
}

From source file:com.surveypanel.utils.DBMessageSource.java

/**
 * build an array of alternative locales for the given locale <br/>
 * result does not contain original locale
 * @param locale the locale to find alternatives for
 * @return an array of alternative locales
 *///from   w  w w .  j  a va2  s  .  com
private Locale[] getAlternativeLocales(Locale locale) {
    Locale[] locales = new Locale[3];
    int count = 0;
    if (locale.getVariant().length() > 0) {
        // add a locale without the variant
        locales[count] = new Locale(locale.getLanguage(), locale.getCountry());
        count++;
    }
    if (locale.getCountry().length() > 0) {
        // add a locale without the country
        locales[count] = new Locale(locale.getLanguage());
        count++;
    }
    if (fallbackLocale != null) {
        locales[count] = fallbackLocale;
    }
    return locales;
}

From source file:de.iew.services.impl.MessageBundleServiceImpl.java

protected MessageBundleStore loadBundle(Locale locale, String basename) {
    List<MessageBundle> messageBundles;
    if (basename == null) {
        messageBundles = this.messageBundleDao.findByLocale(locale.getLanguage(), locale.getCountry());
    } else {//from www.j a  va  2s.com
        messageBundles = this.messageBundleDao.findByLocaleAndBasename(locale.getLanguage(),
                locale.getCountry(), basename);
    }

    MessageBundleStore messageBundleStore = new MessageBundleStore(locale, basename);
    for (MessageBundle messageBundle : messageBundles) {
        messageBundleStore.put(messageBundle);
    }

    return messageBundleStore;
}

From source file:se.anyro.nfc_reader.TagViewer.java

private NdefRecord newTextRecord(String text, Locale locale, boolean encodeInUtf8) {
    byte[] langBytes = locale.getLanguage().getBytes(Charset.forName("US-ASCII"));

    Charset utfEncoding = encodeInUtf8 ? Charset.forName("UTF-8") : Charset.forName("UTF-16");
    byte[] textBytes = text.getBytes(utfEncoding);

    int utfBit = encodeInUtf8 ? 0 : (1 << 7);
    char status = (char) (utfBit + langBytes.length);

    byte[] data = new byte[1 + langBytes.length + textBytes.length];
    data[0] = (byte) status;
    System.arraycopy(langBytes, 0, data, 1, langBytes.length);
    System.arraycopy(textBytes, 0, data, 1 + langBytes.length, textBytes.length);

    return new NdefRecord(NdefRecord.TNF_WELL_KNOWN, NdefRecord.RTD_TEXT, new byte[0], data);
}

From source file:edu.cornell.mannlib.vitro.webapp.filters.WebappDaoFactorySparqlPrep.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
        throws IOException, ServletException {

    if (request.getAttribute("WebappDaoFactorySDBPrep.setup") != null) {
        // don't run multiple times
        filterChain.doFilter(request, response);
        return;/*  w w w .  ja va2 s  .  com*/
    }

    for (Pattern skipPattern : skipPatterns) {
        Matcher match = skipPattern.matcher(((HttpServletRequest) request).getRequestURI());
        if (match.matches()) {
            log.debug("request matched a skipPattern, skipping VitroRequestPrep");
            filterChain.doFilter(request, response);
            return;
        }
    }

    javax.sql.DataSource ds = JenaDataSourceSetupBase.getApplicationDataSource(_ctx);
    StoreDesc storeDesc = (StoreDesc) _ctx.getAttribute("storeDesc");
    OntModelSelector oms = (OntModelSelector) _ctx.getAttribute("unionOntModelSelector");
    String defaultNamespace = (String) _ctx.getAttribute("defaultNamespace");
    Connection sqlConn = null;
    SDBConnection conn = null;
    Store store = null;
    Dataset dataset = null;
    WebappDaoFactory wadf = null;

    try {
        if (ds == null || storeDesc == null || oms == null) {
            throw new RuntimeException("SDB store not property set up");
        }

        try {
            sqlConn = ds.getConnection();
            conn = new SDBConnection(sqlConn);
        } catch (SQLException sqe) {
            throw new RuntimeException("Unable to connect to database", sqe);
        }
        if (conn != null) {
            store = SDBFactory.connectStore(conn, storeDesc);
            dataset = SDBFactory.connectDataset(store);
            VitroRequest vreq = new VitroRequest((HttpServletRequest) request);

            log.info("---------");

            Enumeration<String> headStrs = vreq.getHeaderNames();
            while (headStrs.hasMoreElements()) {
                String head = headStrs.nextElement();
                log.info(head + " : " + vreq.getHeader(head));
            }

            List<String> langs = new ArrayList<String>();

            log.info("Accept-Language: " + vreq.getHeader("Accept-Language"));
            Enumeration<Locale> locs = vreq.getLocales();
            while (locs.hasMoreElements()) {
                Locale locale = locs.nextElement();
                langs.add(locale.toString().replace("_", "-"));
                log.info(locale.toString() + " / " + locale.getLanguage() + " + " + locale.getCountry() + " : "
                        + locale.getDisplayCountry() + " | " + locale.getLanguage() + " : "
                        + locale.getDisplayLanguage());
            }
            WebappDaoFactoryConfig config = new WebappDaoFactoryConfig();
            config.setDefaultNamespace(defaultNamespace);
            config.setPreferredLanguages(langs);

            //okay let's make a graph-backed model
            String endpointURI = ConfigurationProperties.getBean(request)
                    .getProperty("VitroConnection.DataSource.endpointURI");

            Graph g = new SparqlGraphMultilingual(endpointURI, langs);
            //Graph g = new SparqlGraph(endpointURI);

            Model m = ModelFactory.createModelForGraph(g);
            OntModel om = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM, m);
            oms = new SingleContentOntModelSelector(om, oms.getDisplayModel(), oms.getUserAccountsModel());

            dataset = DatasetFactory.create(new SparqlDatasetGraph(endpointURI));

            //DataSource datasource = DatasetFactory.create();
            //datasource.addNamedModel("fake:fake", m);
            //dataset = datasource;         

            vreq.setAssertionsWebappDaoFactory(wadf);

            wadf = new WebappDaoFactoryJena(oms, config);
            //wadf = new WebappDaoFactorySDB(oms, dataset, config);
            vreq.setWebappDaoFactory(wadf);
            vreq.setFullWebappDaoFactory(wadf);
            vreq.setUnfilteredWebappDaoFactory(wadf);
            vreq.setWebappDaoFactory(wadf);
            vreq.setDataset(dataset);
            vreq.setJenaOntModel(om);
            vreq.setOntModelSelector(oms);
        }
    } catch (Throwable t) {
        log.error("Unable to filter request to set up SDB connection", t);
    }

    request.setAttribute("WebappDaoFactorySDBPrep.setup", 1);

    try {
        filterChain.doFilter(request, response);
        return;
    } finally {
        if (conn != null) {
            conn.close();
        }
        if (dataset != null) {
            dataset.close();
        }
        if (store != null) {
            store.close();
        }
        if (wadf != null) {
            wadf.close();
        }
    }

}

From source file:com.smartitengineering.util.opensearch.io.impl.dom.OpenSearchDescriptorWriter.java

protected String getLocaleString(Locale language) {
    if (language == null) {
        return null;
    } else {/*from ww w  .j av a 2  s . c o m*/
        StringBuilder localeString = new StringBuilder("");
        if (StringUtils.isNotBlank(language.getLanguage())) {
            localeString.append(language.getLanguage());
            if (StringUtils.isNotBlank(language.getCountry())) {
                localeString.append('-').append(language.getCountry().toLowerCase());
            }
        }
        return localeString.toString();
    }
}

From source file:net.sourceforge.fenixedu.presentationTier.backBeans.delegate.EvaluationsForDelegatesConsultingBackingBean.java

public String getDegreeName() {
    final Locale locale = FacesContext.getCurrentInstance().getViewRoot().getLocale();
    return locale.getLanguage().equals(Locale.ENGLISH.getLanguage())
            ? getDegree().getNameFor(getExecutionYear()).getContent(MultiLanguageString.en)
            : getDegree().getNameFor(getExecutionYear()).getContent(MultiLanguageString.pt);
}

From source file:fr.free.movierenamer.scrapper.impl.trailer.VideoDetectiveScrapper.java

@Override
protected List<Trailer> searchTrailer(Media media) throws Exception {

    List<Trailer> trailers = new ArrayList<Trailer>();
    String search = media.getOriginalName();
    if (search == null || search.equals("")) {
        search = media.getName();//w  w  w .  jav a2 s .  c  o  m
    }

    URL searchUrl = new URL("http", host,
            "/browse?filter=mediatype%3aMovie+Alternate+Version&q=" + URIRequest.encode(search));
    Document dom = URIRequest.getHtmlDocument(searchUrl.toURI());
    List<Node> nodes = XPathUtils.selectNodes("//DIV[contains(@class, 'durationwrapper')]", dom);

    for (Node node : nodes) {
        Node info = XPathUtils.selectNode("DIV[@class='duration']//A[contains(@href, '/movies/')]", node);
        if (info != null) {

            String title = info.getTextContent();
            if (!isTrailerof(title, media)) {
                continue;
            }

            String runtime = XPathUtils.selectString("DIV[@class='durationtext']", node).trim();

            URL thumbUrl = null;
            String thumb = XPathUtils.selectString("A[contains(@href, '/movies/')]/IMG/@src", node);
            if (thumb != null && !thumb.equals("")) {
                try {
                    thumbUrl = new URL(thumb);
                } catch (MalformedURLException ex) {
                }
            }

            URL trailerUrl = null;
            String turlStr = XPathUtils.getAttribute("href", info);
            try {
                trailerUrl = new URL("http", host, turlStr);
            } catch (MalformedURLException ex) {
            }

            Node lnode = XPathUtils
                    .selectNode("DIV[@class='duration']//DIV[last()]/text()[preceding-sibling::BR]", node);
            AvailableLanguages lang = null;
            if (lnode != null) {
                Locale local = LocaleUtils.findLanguage(lnode.getTextContent().trim());
                if (local != null) {
                    try {
                        lang = AvailableLanguages.valueOf(local.getLanguage());
                    } catch (Exception ex) {
                    }
                }
            }

            trailers.add(new Trailer(title, runtime, name, thumbUrl, trailerUrl, lang));
        }
    }

    return trailers;
}