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:com.andryr.musicplayer.activities.MusicPicker.java

private void getSongList() {
    ContentResolver resolver = getContentResolver();
    Uri musicUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;

    Cursor cursor = resolver.query(musicUri, sProjection, null, null, null);

    if (cursor != null && cursor.moveToFirst()) {
        int idCol = cursor.getColumnIndex(MediaStore.Audio.Playlists.Members.AUDIO_ID);
        if (idCol == -1) {
            idCol = cursor.getColumnIndex(MediaStore.Audio.Media._ID);
        }/*from  w w w  .  jav a  2s.com*/
        int titleCol = cursor.getColumnIndex(MediaStore.Audio.Media.TITLE);
        int artistCol = cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST);
        int albumCol = cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM);
        int albumIdCol = cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM_ID);
        int trackCol = cursor.getColumnIndex(MediaStore.Audio.Media.TRACK);

        int durationCol = cursor.getColumnIndex(MediaStore.Audio.Media.DURATION);

        do {
            long id = cursor.getLong(idCol);
            String title = cursor.getString(titleCol);

            String artist = cursor.getString(artistCol);

            String album = cursor.getString(albumCol);

            long albumId = cursor.getLong(albumIdCol);

            int track = cursor.getInt(trackCol);

            long duration = cursor.getLong(durationCol);

            mSongList.add(new Song(id, title, artist, album, albumId, track, duration));
        } while (cursor.moveToNext());

        Collections.sort(mSongList, new Comparator<Song>() {

            @Override
            public int compare(Song lhs, Song rhs) {
                Collator c = Collator.getInstance(Locale.getDefault());
                c.setStrength(Collator.PRIMARY);
                return c.compare(lhs.getTitle(), rhs.getTitle());
            }
        });

    }
    if (cursor != null) {
        cursor.close();
    }
}

From source file:com.couchbase.lite.CollationTest.java

public void testCollateJapaneseStrings() {
    int mode = kJsonCollator_Unicode;

    // en_US/* w  w  w. j  av  a2 s  .  c  o  m*/
    Collator c = Collator.getInstance(new Locale("en_US"));
    Assert.assertEquals(-1, SQLiteJsonCollator.testCollate(mode, encode("?"), encode("?")));
    Assert.assertEquals(1, SQLiteJsonCollator.testCollate(mode, encode("?"), encode("?")));
    Assert.assertEquals(0, SQLiteJsonCollator.testCollate(mode, encode("?"), encode("?")));
    Assert.assertEquals(c.compare("", ""),
            SQLiteJsonCollator.testCollate(mode, encode(""), encode("")));
    Assert.assertEquals(c.compare("?", ""),
            SQLiteJsonCollator.testCollate(mode, encode("?"), encode("")));
    Assert.assertEquals(c.compare("?", ""),
            SQLiteJsonCollator.testCollate(mode, encode("?"), encode("")));
    Assert.assertEquals(c.compare("", ""),
            SQLiteJsonCollator.testCollate(mode, encode(""), encode("")));
    Assert.assertEquals(c.compare("", "?"),
            SQLiteJsonCollator.testCollate(mode, encode(""), encode("?")));
    Assert.assertEquals(c.compare("", "?"),
            SQLiteJsonCollator.testCollate(mode, encode(""), encode("?")));
    Assert.assertEquals(c.compare("", ""),
            SQLiteJsonCollator.testCollate(mode, encode(""), encode("")));

    // ja
    Locale locale = new Locale("ja");
    String localeStr = locale.toString();
    Collator c1 = Collator.getInstance(locale);
    Assert.assertEquals(-1, SQLiteJsonCollator.testCollate(mode, localeStr, encode("?"), encode("?")));
    Assert.assertEquals(1, SQLiteJsonCollator.testCollate(mode, localeStr, encode("?"), encode("?")));
    Assert.assertEquals(0, SQLiteJsonCollator.testCollate(mode, localeStr, encode("?"), encode("?")));
    Assert.assertEquals(c1.compare("", ""),
            SQLiteJsonCollator.testCollate(mode, localeStr, encode(""), encode("")));
    Assert.assertEquals(c1.compare("?", ""),
            SQLiteJsonCollator.testCollate(mode, localeStr, encode("?"), encode("")));
    Assert.assertEquals(c1.compare("?", ""),
            SQLiteJsonCollator.testCollate(mode, localeStr, encode("?"), encode("")));
    Assert.assertEquals(c1.compare("", ""),
            SQLiteJsonCollator.testCollate(mode, localeStr, encode(""), encode("")));
    Assert.assertEquals(c1.compare("", "?"),
            SQLiteJsonCollator.testCollate(mode, localeStr, encode(""), encode("?")));
    Assert.assertEquals(c1.compare("", "?"),
            SQLiteJsonCollator.testCollate(mode, localeStr, encode(""), encode("?")));
    Assert.assertEquals(c1.compare("", ""),
            SQLiteJsonCollator.testCollate(mode, localeStr, encode(""), encode("")));
}

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

/**
 * Create a cached collator with the given character statistics.
 *
 * @param locale     the wanted locale for the Collator.
 * @param mostCommon the most common characters for the given locale in the
 *                   setting where the collator is used. It can contain any
 *                   number of characters.
 *                   See the class documentation for details.
 *                   Duplicate characters are removed.
 *                   Example: "eaoi 0ntr1"...
 *///  w  w  w.j a v a  2  s .  co  m
public CachedCollator(Locale locale, String mostCommon) {
    log.debug("Creating collator for locale '" + locale + "' with most common characters '" + mostCommon + "'");
    subCollator = Collator.getInstance(locale);
    buildCache(mostCommon);
}

From source file:com.alkacon.opencms.formgenerator.database.export.CmsCvsExportBean.java

/**
 * Returns the CSV export file content.<p> 
 * //from  w  ww. ja  v a 2s.c  om
 * @param formId the current selected web form
 * @param locale the current local
 * 
 * @return the CSV export file content
 * 
 * @throws SQLException if something goes wrong 
 */
public String exportData(String formId, Locale locale) throws SQLException {

    /*
     * TODO: Access the CmsForm (or CmsFormHandler) and put out all 
     * fields in the exact order - put fields that do not exist any longer 
     * to the back (note: readAllFormFieldNames is required for the old values). 
     */

    StringBuffer result = new StringBuffer();
    CmsModule module = OpenCms.getModuleManager().getModule(CmsForm.MODULE_NAME);

    // time format: 
    DateFormat df = null;
    String formatString = module.getParameter(CmsForm.MODULE_PARAM_EXPORT_TIMEFORMAT);
    if (CmsStringUtil.isNotEmpty(formatString)) {
        try {
            df = new SimpleDateFormat(formatString);
        } catch (IllegalArgumentException iae) {
            LOG.warn(Messages.get().getBundle().key(Messages.LOG_WARN_EXPORT_DATEFORMAT_ILLEGAL_2,
                    new Object[] { CmsForm.MODULE_PARAM_EXPORT_TIMEFORMAT, formatString }));
        }
    }

    // line separator: 
    boolean isWindowsLineSeparator = false;
    boolean isUnixLineSeparator = false;

    String lineSeparatorParam = module.getParameter(CmsForm.MODULE_PARAM_EXPORTLINESEPARATOR);
    if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(lineSeparatorParam)) {
        if (lineSeparatorParam.equals(CmsForm.MODULE_PARAMVALUE_EXPORTLINESEPARATOR_WINDOWS)) {
            isWindowsLineSeparator = true;
        } else if (lineSeparatorParam.equals(CmsForm.MODULE_PARAMVALUE_EXPORTLINESEPARATOR_UNIX)
                || lineSeparatorParam.equals(CmsForm.MODULE_PARAMVALUE_EXPORTLINESEPARATOR_EXCEL)) {
            isUnixLineSeparator = true;
        }
    }

    // export numbers as string:
    String nasParam = module.getParameter(CmsForm.MODULE_PARAM_EXPORT_NUMBERASSTRING, CmsStringUtil.FALSE);
    boolean numberAsString = Boolean.valueOf(nasParam).booleanValue();

    // csv delimiter
    String lineSeparator = EXCEL_DEFAULT_CSV_DELMITER;
    String configLineSeparator = module.getParameter(CmsForm.MODULE_PARAM_CSV_DELIMITER);
    if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(configLineSeparator)) {

        lineSeparator = configLineSeparator.trim();
    }

    // get the column names
    List<String> columnNames = CmsFormDataAccess.getInstance().readFormFieldNames(formId,
            getStartTime().getTime(), getEndTime().getTime());
    Collections.sort(columnNames, Collator.getInstance(locale));

    // get the entries
    List<CmsFormDataBean> dataEntries = CmsFormDataAccess.getInstance().readForms(formId,
            getStartTime().getTime(), getEndTime().getTime());

    // loop 1 - write the headers:
    result.append(escapeExcelCsv("Creation date", numberAsString));
    result.append(lineSeparator);
    result.append(escapeExcelCsv("Resource path", numberAsString));
    result.append(lineSeparator);
    result.append(escapeExcelCsv("Resource UUID", numberAsString));
    result.append(lineSeparator);
    Iterator<String> itColumns = columnNames.iterator();
    while (itColumns.hasNext()) {
        String columnName = itColumns.next();
        // skip empty columns (previous versions saved CmsEmptyField with empty values which will not be deleted):
        if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(columnName)) {
            columnName = escapeExcelCsv(columnName, numberAsString);
            result.append(columnName);
            if (itColumns.hasNext()) {
                result.append(lineSeparator);
            }
        }
    }
    result.append("\r\n");
    // loop 2 - write the data:
    Iterator<CmsFormDataBean> itRows = dataEntries.iterator();
    String path;
    CmsUUID uuid = null;
    while (itRows.hasNext()) {
        CmsFormDataBean row = itRows.next();
        // create an entry for each column, even if some rows (data sets) 
        // do not contain the field value because it was 
        // a) not entered 
        // b) the form was changed in structure over time 
        // c) developer errors,  hw /sw problems... 
        Date creationDate = new Date(row.getDateCreated());
        if (df == null) {
            result.append(creationDate);
        } else {
            result.append(df.format(creationDate));
        }
        DateFormat.getDateTimeInstance();
        result.append(lineSeparator);
        uuid = row.getResourceId();
        try {
            path = m_cms.readResource(uuid).getRootPath();
        } catch (Exception e) {
            path = row.getResourceId().toString();
        }
        result.append(path);
        result.append(lineSeparator);
        result.append(String.valueOf(uuid));
        result.append(lineSeparator);
        itColumns = columnNames.iterator();
        while (itColumns.hasNext()) {
            String columnName = itColumns.next();
            // skip empty columns (previous versions saved CmsEmptyField with empty values which will not be deleted):
            if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(columnName)) {

                String value = row.getFieldValue(columnName);
                if (value != null) {
                    if (isWindowsLineSeparator) {
                        value = transformWindowsLineseparator(value);
                    } else if (isUnixLineSeparator) {
                        value = transformUnixLineseparator(value);
                    }
                    value = escapeExcelCsv(value, numberAsString);
                    result.append(value);
                }
                if (itColumns.hasNext()) {
                    result.append(lineSeparator);
                }
            }
        }
        result.append("\r\n");
    }
    return result.toString();
}

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

/**
 * Create a cached collator with the given character statistics.
 *
 * @param locale     the wanted locale for the Collator.
 * @param mostCommon the most common characters for the given locale in the
 *                   setting where the collator is used. It can contain any
 *                   number of characters.
 *                   See the class documentation for details.
 *                   Duplicate characters are removed.
 *                   Example: "eaoi 0ntr1"...
 * @param spaceFirst if true, the generated Collator is modified to sort
 *                   spaces before other characters: {"a b", "aa"}.
 *//*from www  .j  a  v  a 2  s  .  c  o m*/
public CachedCollator(Locale locale, String mostCommon, boolean spaceFirst) {
    subCollator = Collator.getInstance(locale);
    if (spaceFirst) {
        subCollator = fixCollator(subCollator, false);
    }
    buildCache(mostCommon);
}

From source file:de.blizzy.documentr.web.Functions.java

public static List<JspMacroDescriptor> getMacros() {
    List<IMacroDescriptor> descs = Lists.newArrayList(macroFactory.getDescriptors());
    final Locale locale = LocaleContextHolder.getLocale();
    final Collator collator = Collator.getInstance(locale);
    Collections.sort(descs, new Comparator<IMacroDescriptor>() {
        @Override//  w w  w.  ja  v  a 2s.c  o m
        public int compare(IMacroDescriptor d1, IMacroDescriptor d2) {
            String title1 = d1.getTitle(locale);
            String title2 = d2.getTitle(locale);
            return collator.compare(title1, title2);
        }
    });
    Function<IMacroDescriptor, JspMacroDescriptor> function = new Function<IMacroDescriptor, JspMacroDescriptor>() {
        @Override
        public JspMacroDescriptor apply(IMacroDescriptor descriptor) {
            return new JspMacroDescriptor(descriptor, locale);
        }
    };
    return Lists.transform(descs, function);
}

From source file:fr.mcc.ginco.soap.SOAPThesaurusTermServiceImpl.java

@Override
public List<ReducedThesaurusTerm> getTermsBeginWithSomeStringByThesaurus(String request, String thesaurusId,
        Boolean preferredTermOnly, int startIndex, int limit, TermStatusEnum status, Boolean withNotes) {
    if (StringUtils.isNotEmpty(request) && limit != 0) {
        try {//from  w  ww .j av a2  s . c om
            request = ClientUtils.escapeQueryChars(request);
            String requestFormat = SolrField.LEXICALVALUE_STR + ":" + request + "*";
            List<ReducedThesaurusTerm> reducedThesaurusTermList = new ArrayList<ReducedThesaurusTerm>();
            SortCriteria crit = new SortCriteria(SolrField.LEXICALVALUE, SolrConstants.ASCENDING);
            Integer searchType = SearchEntityType.TERM;
            if (preferredTermOnly) {
                searchType = SearchEntityType.TERM_PREF;
            }
            Integer intStatus = null;
            if (status != null) {
                intStatus = status.getStatus();
            }
            SearchResultList searchResultList = searcherService.search(requestFormat, searchType, thesaurusId,
                    intStatus, null, null, null, crit, startIndex, limit);
            if (searchResultList != null) {
                for (SearchResult searchResult : searchResultList) {
                    ReducedThesaurusTerm reducedThesaurusTerm = new ReducedThesaurusTerm();

                    reducedThesaurusTerm.setIdentifier(searchResult.getIdentifier());
                    reducedThesaurusTerm.setConceptId(searchResult.getConceptId());
                    reducedThesaurusTerm.setLexicalValue(searchResult.getLexicalValue());
                    reducedThesaurusTerm.setLanguageId(searchResult.getLanguages().get(0));
                    reducedThesaurusTerm.setStatus(TermStatusEnum.getStatusByCode(searchResult.getStatus()));
                    if (withNotes != null && withNotes == true) {
                        addNotesToTerm(reducedThesaurusTerm);
                    }
                    reducedThesaurusTermList.add(reducedThesaurusTerm);
                }
            }
            Collections.sort(reducedThesaurusTermList, new Comparator<ReducedThesaurusTerm>() {
                Collator frCollator = Collator.getInstance(Locale.FRENCH);

                public int compare(ReducedThesaurusTerm t1, ReducedThesaurusTerm t2) {
                    return frCollator.compare(t1.getLexicalValue(), t2.getLexicalValue());
                }
            });
            return reducedThesaurusTermList;
        } catch (SolrServerException e) {
            throw new TechnicalException("Search exception", e);
        }
    } else {
        throw new BusinessException("One or more parameters are empty", "empty-parameters");
    }
}

From source file:org.eclipse.smarthome.io.rest.core.extensions.ExtensionResource.java

private Set<ExtensionType> getAllExtensionTypes(Locale locale) {
    final Collator coll = Collator.getInstance(locale);
    coll.setStrength(Collator.PRIMARY);
    Set<ExtensionType> ret = new TreeSet<>(new Comparator<ExtensionType>() {
        @Override/*from  w  w w . j  av a2  s. c o  m*/
        public int compare(ExtensionType o1, ExtensionType o2) {
            return coll.compare(o1.getLabel(), o2.getLabel());
        }
    });
    for (ExtensionService extensionService : extensionServices) {
        ret.addAll(extensionService.getTypes(locale));
    }
    return ret;
}

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

/**
 * Create a cached collator with the given character statistics. This uses
 * the characters from 0x20 to 0xFF as the most common characters. It is
 * recommended to use {@link #CachedCollator(Locale, String)} instead, in
 * order to achieve maximum speed-up and valid comparisons.
 *
 * @param locale     the wanted locale for the Collator.
 * @param spaceFirst if true, the generated Collator is modified to sort
 *                   spaces before other characters: {"a b", "aa"}.
 *//*from   ww  w . ja va  2  s .  co m*/
public CachedCollator(Locale locale, boolean spaceFirst) {
    subCollator = Collator.getInstance(locale);
    if (spaceFirst) {
        subCollator = fixCollator(subCollator, false);
    }
    buildCache(getBasicChars());
}

From source file:de.geeksfactory.opacclient.objects.Library.java

@Override
public int compareTo(Library arg0) {
    Collator deCollator = Collator.getInstance(Locale.GERMAN);
    deCollator.setStrength(Collator.TERTIARY);

    int g = deCollator.compare(country, arg0.getCountry());
    if (g == 0) {
        g = deCollator.compare(state, arg0.getState());
        if (g == 0) {
            g = deCollator.compare(city, arg0.getCity());
            if (g == 0) {
                g = deCollator.compare(title, arg0.getTitle());
            }/*from   w  ww .  j  a va  2  s  .c o m*/
        }
    }
    return g;
}