Example usage for java.text Collator getInstance

List of usage examples for java.text Collator getInstance

Introduction

In this page you can find the example usage for java.text Collator getInstance.

Prototype

public static Collator getInstance(Locale desiredLocale) 

Source Link

Document

Gets the Collator for the desired locale.

Usage

From source file:net.felsing.client_cert.GetCountries.java

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    final Locale defaultLanguage = Locale.ENGLISH;
    String bestLanguage = null;//ww w . j av  a 2s  . com
    resp.setContentType("application/json; charset=UTF-8");
    resp.setCharacterEncoding("UTF-8");

    final String acceptLanguage = StringEscapeUtils.escapeJava(req.getHeader("Accept-Language"));

    List<Locale.LanguageRange> languageRanges = Locale.LanguageRange.parse(acceptLanguage);
    for (Locale.LanguageRange l : languageRanges) {
        try {
            if (bestLanguage == null) {
                Locale locale = new Locale(l.getRange().split("-")[0]);
                bestLanguage = locale.getISO3Language();
                logger.debug("bestLanguage: " + bestLanguage);
                usedLocale = locale;
            }
        } catch (Exception e) {
            // do nothing
        }
    }

    if (bestLanguage == null) {
        logger.debug("No sufficient language found for " + acceptLanguage);
        bestLanguage = defaultLanguage.getISO3Language();
        usedLocale = Locale.ENGLISH;
    }

    logger.debug("usedLocale: " + usedLocale.getISO3Language());

    PrintWriter pw = resp.getWriter();
    loadFromJson(context);
    List<Country> countriesList = new ArrayList<>();
    for (JsonElement jsonElement : countries) {
        String cca2 = jsonElement.getAsJsonObject().get("cca2").toString().replaceAll("\\\"", "");
        cca2 = cca2.replaceAll("\\\\", "");

        Country countryItem = new Country();
        try {
            countryItem.name = jsonElement.getAsJsonObject().get("name").getAsJsonObject().get(bestLanguage)
                    .getAsJsonObject().get("common").getAsString();
        } catch (NullPointerException e) {
            countryItem.name = jsonElement.getAsJsonObject().get("name_").getAsString();
        }
        countryItem.cca2 = cca2;
        countriesList.add(countryItem);
    }
    Collator coll = Collator.getInstance(usedLocale);
    coll.setStrength(Collator.PRIMARY);
    Collections.sort(countriesList);
    pw.print(new Gson().toJson(countriesList));
    pw.flush();
}

From source file:br.ufrgs.ufrgsmapas.libs.SearchBox.java

/**
 * Create a searchbox with params and a style
 * @param context Context/*from  w w w  .  j  a va 2  s . com*/
 * @param attrs Attributes
 * @param defStyle Style
 */
public SearchBox(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
    inflate(context, R.layout.searchbox, this);
    this.searchOpen = false;
    this.isMic = true;
    this.materialMenu = (MaterialMenuView) findViewById(R.id.material_menu_button);
    this.logo = (TextView) findViewById(R.id.logo);
    this.search = (EditText) findViewById(R.id.search);
    this.results = (ListView) findViewById(R.id.results);
    this.context = context;
    this.pb = (ProgressBar) findViewById(R.id.pb);
    this.mic = (ImageView) findViewById(R.id.mic);
    this.drawerLogo = (ImageView) findViewById(R.id.drawer_logo);

    mCollator = Collator.getInstance(new Locale("pt", "BR"));
    mCollator.setStrength(Collator.PRIMARY);

    materialMenu.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            if (searchOpen) {
                toggleSearch();
            } else {
                if (menuListener != null)
                    menuListener.onMenuClick();
            }
        }

    });
    resultList = new ArrayList<SearchResult>();
    results.setAdapter(new SearchAdapter(context, resultList));
    animate = true;
    isVoiceRecognitionIntentSupported = isIntentAvailable(context,
            new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH));
    logo.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            toggleSearch();
        }

    });
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
        RelativeLayout searchRoot = (RelativeLayout) findViewById(R.id.search_root);
        LayoutTransition lt = new LayoutTransition();
        lt.setDuration(100);
        searchRoot.setLayoutTransition(lt);
    }
    searchables = new ArrayList<SearchResult>();
    search.setOnEditorActionListener(new OnEditorActionListener() {
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                search(getSearchText());
                return true;
            }
            return false;
        }
    });
    search.setOnKeyListener(new OnKeyListener() {
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            if (keyCode == KeyEvent.KEYCODE_ENTER) {
                if (TextUtils.isEmpty(getSearchText())) {
                    toggleSearch();
                } else {
                    search(getSearchText());
                }
                return true;
            }
            return false;
        }
    });
    logoText = "Logo";
    micStateChanged();
    mic.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            if (voiceRecognitionListener != null) {
                voiceRecognitionListener.onClick();
            } else {
                micClick();
            }
        }
    });
}

From source file:org.apache.solr.analysis.CollationKeyFilterFactory.java

private Collator createFromLocale(String language, String country, String variant) {
    Locale locale;// w ww  .  j a v  a 2  s  . c o m

    if (language != null && country == null && variant != null)
        throw new SolrException(ErrorCode.SERVER_ERROR, "To specify variant, country is required");
    else if (language != null && country != null && variant != null)
        locale = new Locale(language, country, variant);
    else if (language != null && country != null)
        locale = new Locale(language, country);
    else
        locale = new Locale(language);

    return Collator.getInstance(locale);
}

From source file:me.piebridge.bible.Bible.java

public void checkLocale() {
    Locale locale = Locale.getDefault();
    collator = Collator.getInstance(Locale.getDefault());
    if (!locale.equals(lastLocale)) {
        lastLocale = locale;//w w  w .  j a  v  a2 s. co  m
        setResources();
    }
}

From source file:fr.gouv.culture.thesaurus.util.template.ThesaurusSorter.java

/**
 * Tri des ressources par leur libell. Les valeurs <code>null</code> sont
 * conserves et mises en tte de la collection.
 * /*from ww w  .  ja v  a 2  s.  c om*/
 * @param entries
 *            Ressources  trier par libell (ou <code>null</code>)
 * @param prioritizedLanguages
 *            Langues prioritaires (la valeur <code>null</code> reprsente
 *            la langue neutre)
 * @return Ressources tries par libell, ou <code>null</code> si la liste
 *         des ressources en entre est <code>null</code>
 */
public <T extends Entry> Collection<T> sortEntriesByLabel(final Collection<T> entries,
        final Locale[] prioritizedLanguages, final boolean prioritized) {
    Collection<T> sortedEntries;

    if (entries == null) {
        sortedEntries = null;
    } else {
        int nullEntries = 0;
        final List<SortItemWrapper<T>> wrappers = new ArrayList<SortItemWrapper<T>>(entries.size());
        final Iterator<T> iterator = entries.iterator();

        while (iterator.hasNext()) {
            final T entry = iterator.next();

            if (entry == null) {
                nullEntries++;
            } else {
                final LocalizedString label = getEntryLabel(entry, prioritizedLanguages);
                final String language = label.getLanguage();

                final Collator collator = language == null ? null : Collator.getInstance(getLocale(language));

                wrappers.add(new SortItemWrapper<T>(entry, label, collator,
                        prioritized ? LangUtils.convertLocalesToString(LangUtils.expand(prioritizedLanguages))
                                : null));
            }
        }

        Collections.sort(wrappers);

        sortedEntries = new ArrayList<T>(wrappers.size() + nullEntries);
        while (nullEntries-- > 0) {
            sortedEntries.add(null);
        }
        for (final SortItemWrapper<T> wrapper : wrappers) {
            sortedEntries.add(wrapper.getData());
        }
    }

    return sortedEntries;
}

From source file:dk.statsbiblioteket.util.CachedCollator.java

/**
 * Create a cached collator with the characters from 0x20 to 0xFF
 * as the most common characters. It is recommended to use the constructor
 * {@link #CachedCollator(Locale, String)} instead, in order to achieve
 * maximum speed-up and valid comparisons.
 *
 * @param locale the wanted locale for the Collator.
 *//*from  w  w  w  . j  a v a2  s . co m*/
public CachedCollator(Locale locale) {
    log.debug("Creating default character collator for locale '" + locale + "'");
    subCollator = Collator.getInstance(locale);
    buildCache(getBasicChars());
}

From source file:de.ingrid.portal.portlets.mdek.MdekPortalAdminPortlet.java

public void doViewNew(javax.portlet.RenderRequest request, javax.portlet.RenderResponse response)
        throws PortletException, IOException {
    setDefaultViewPage(TEMPLATE_NEW);//  w w w.j a v  a 2s.co  m

    Context context = getContext(request);
    List<String> plugIdList = getUnconnectedPlugIdList(request);
    List<String> userNameList = getUnconnectedUserList();
    Collections.sort(plugIdList);
    Collections.sort(userNameList, Collator.getInstance(Locale.GERMAN));

    ResourceBundle resourceBundle = getPortletConfig().getResourceBundle(request.getLocale());
    context.put("MESSAGES", resourceBundle);

    PortletPreferences prefs = request.getPreferences();
    String myTitleKey = prefs.getValue("titleKey", "mdek.title.portaladmin");
    response.setTitle(resourceBundle.getString(myTitleKey));

    context.put("plugIdList", plugIdList);
    context.put("userNameList", userNameList);
}

From source file:controllers.nwbib.Application.java

private static List<String> cleanSortUnique(List<JsonNode> topics) {
    List<String> filtered = topics.stream().map(topic -> topic.textValue().replaceAll("\\([\\d,]+\\)$", ""))
            .filter(topic -> !topic.trim().startsWith(":")).map(v -> v.trim()).collect(Collectors.toList());
    SortedSet<String> sortedUnique = new TreeSet<>(
            (s1, s2) -> Collator.getInstance(Locale.GERMAN).compare(s1, s2));
    sortedUnique.addAll(filtered);//from w ww.  j a  v a2s .  c  o m
    return new ArrayList<>(sortedUnique);
}

From source file:com.powers.wsexplorer.gui.GUIUtil.java

public static Listener createTextSortListener(final Table table, final Map<String, String> map,
        final boolean sortOnValues) {

    Listener sortListener = new Listener() {
        public void handleEvent(Event e) {

            final int direction = table.getSortDirection();

            Collator collator = Collator.getInstance(Locale.getDefault());
            TableColumn column = (TableColumn) e.widget;

            Set<String> keys = null;
            List<String> l = new LinkedList<String>();
            Iterator<String> itr = null;

            if (sortOnValues) {

                TreeMap<String, String> tm = new TreeMap<String, String>(
                        new MapValueComparator(map, direction == SWT.DOWN));
                tm.putAll(map);//from   ww w .j a  va2s  . co m

                if (direction == SWT.DOWN) {
                    table.setSortDirection(SWT.UP);
                } else {
                    table.setSortDirection(SWT.DOWN);
                }

                itr = tm.keySet().iterator();
            } else {

                keys = map.keySet();
                l.addAll(keys);
                Collections.sort(l, collator);

                if (direction == SWT.DOWN) {
                    Collections.reverse(l);
                    table.setSortDirection(SWT.UP);
                } else {
                    table.setSortDirection(SWT.DOWN);
                }

                itr = l.iterator();
            }

            // remove all table data
            table.removeAll();

            String key = null;
            String value = null;

            while (itr.hasNext()) {
                key = itr.next();
                if (StringUtils.isNotBlank(key)) {
                    TableItem ti = new TableItem(table, SWT.BORDER);
                    ti.setText(0, key);
                    value = map.get(key);
                    if (StringUtils.isNotBlank(value)) {
                        ti.setText(1, value);
                    }
                }

            }

            table.setSortColumn(column);
        }
    };

    return sortListener;
}

From source file:org.apache.solr.schema.CollationField.java

/**
 * Create a locale from language, with optional country and variant.
 * Then return the appropriate collator for the locale.
 *///from w  w w .  j a  va 2  s.c o  m
private Collator createFromLocale(String language, String country, String variant) {
    Locale locale;

    if (language != null && country == null && variant != null)
        throw new SolrException(ErrorCode.SERVER_ERROR, "To specify variant, country is required");
    else if (language != null && country != null && variant != null)
        locale = new Locale(language, country, variant);
    else if (language != null && country != null)
        locale = new Locale(language, country);
    else
        locale = new Locale(language);

    return Collator.getInstance(locale);
}