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:org.alfresco.repo.jscript.ScriptNode.java

/**
 * Performs a locale-sensitive sort by name of a node array
 * @param nodes the node array/*from w w w. j  a v  a 2  s  . c om*/
 */
private static void sort(Object[] nodes) {
    final Collator col = Collator.getInstance(I18NUtil.getLocale());
    Arrays.sort(nodes, new Comparator<Object>() {
        @Override
        public int compare(Object o1, Object o2) {
            return col.compare(((ScriptNode) o1).getName(), ((ScriptNode) o2).getName());
        }
    });
}

From source file:org.talend.dataprofiler.core.ui.editor.analysis.drilldown.DrillDownResultEditor.java

private void addSorter(final Table table, final TableColumn column) {
    column.addListener(SWT.Selection, new Listener() {

        boolean isAscend = true;

        Collator comparator = Collator.getInstance(Locale.getDefault());

        public void handleEvent(Event event) {
            int columnIndex = getColumnIndex(table, column);
            TableItem[] items = table.getItems();
            int length = "...".equals(items[items.length - 1].getText(columnIndex)) ? items.length - 1 //$NON-NLS-1$
                    : items.length;// w w w .  j av a2s  .  c  om
            for (int i = 1; i < length; i++) {
                String value2 = items[i].getText(columnIndex);
                for (int j = 0; j < i; j++) {
                    String value1 = items[j].getText(columnIndex);
                    boolean isLessThan = true;

                    if (StringUtils.isNumeric(value2) && StringUtils.isNotEmpty(value2)
                            && StringUtils.isNumeric(value1) && StringUtils.isNotEmpty(value1)) {
                        isLessThan = Long.valueOf(value2).compareTo(Long.valueOf(value1)) < 0;
                    } else {
                        isLessThan = comparator.compare(value2, value1) < 0;
                    }
                    if ((isAscend && isLessThan) || (!isAscend && !isLessThan)) {
                        String[] values = getTableItemText(table, items[i]);
                        Object obj = items[i].getData();
                        items[i].dispose();
                        TableItem item = new TableItem(table, SWT.NONE, j);
                        item.setText(values);
                        item.setData(obj);
                        items = table.getItems();
                        break;
                    }
                }
            }

            table.setSortColumn(column);
            table.setSortDirection((isAscend ? SWT.UP : SWT.DOWN));
            isAscend = !isAscend;

        }
    });
}

From source file:jackpal.androidterm.Term.java

private String makePathFromBundle(Bundle extras) {
    if (extras == null || extras.size() == 0) {
        return "";
    }/*from  w  w  w  . j  a  v  a  2 s . c o m*/

    String[] keys = new String[extras.size()];
    keys = extras.keySet().toArray(keys);
    Collator collator = Collator.getInstance(Locale.US);
    Arrays.sort(keys, collator);

    StringBuilder path = new StringBuilder();
    for (String key : keys) {
        String dir = extras.getString(key);
        if (dir != null && !dir.equals("")) {
            path.append(dir);
            path.append(":");
        }
    }

    return path.substring(0, path.length() - 1);
}

From source file:controllers.nwbib.Application.java

/**
 * @param q Query to search in all fields
 * @param person Query for a person associated with the resource
 * @param name Query for the resource name (title)
 * @param subject Query for the resource subject
 * @param id Query for the resource id//from w ww.  j ava 2  s. c  o  m
 * @param publisher Query for the resource publisher
 * @param issued Query for the resource issued year
 * @param medium Query for the resource medium
 * @param nwbibspatial Query for the resource nwbibspatial classification
 * @param nwbibsubject Query for the resource nwbibsubject classification
 * @param from The page start (offset of page of resource to return)
 * @param size The page size (size of page of resource to return)
 * @param owner Owner filter for resource queries
 * @param t Type filter for resource queries
 * @param field The facet field (the field to facet over)
 * @param sort Sorting order for results ("newest", "oldest", "" -> relevance)
 * @param set The set, overrides the default NWBib set if not empty
 * @param location A polygon describing the subject area of the resources
 * @param word A word, a concept from the hbz union catalog
 * @param corporation A corporation associated with the resource
 * @param raw A query string that's directly (unprocessed) passed to ES
 * @return The search results
 */
public static Promise<Result> facets(String q, String person, String name, String subject, String id,
        String publisher, String issued, String medium, String nwbibspatial, String nwbibsubject, int from,
        int size, String owner, String t, String field, String sort, String set, String location, String word,
        String corporation, String raw) {

    String key = String.format("facets.%s.%s.%s.%s.%s.%s.%s.%s.%s.%s.%s.%s.%s.%s.%s.%s.%s.%s", field, q, person,
            name, id, publisher, set, location, word, corporation, raw, subject, issued, medium, nwbibspatial,
            nwbibsubject, owner, t);
    Result cachedResult = (Result) Cache.get(key);
    if (cachedResult != null) {
        return Promise.promise(() -> cachedResult);
    }

    String labelTemplate = "<span class='%s'/>&nbsp;%s (%s)";

    Function<JsonNode, Pair<JsonNode, String>> toLabel = json -> {
        String term = json.get("term").asText();
        int count = json.get("count").asInt();
        String icon = Lobid.facetIcon(Arrays.asList(term), field);
        String label = Lobid.facetLabel(Arrays.asList(term), field, "");
        String fullLabel = String.format(labelTemplate, icon, label, count);
        return Pair.of(json, fullLabel);
    };

    Predicate<Pair<JsonNode, String>> labelled = pair -> {
        JsonNode json = pair.getLeft();
        String label = pair.getRight();
        int count = json.get("count").asInt();
        return (!label.contains("http") || label.contains("nwbib"))
                && label.length() > String.format(labelTemplate, "", "", count).length();
    };

    Collator collator = Collator.getInstance(Locale.GERMAN);
    Comparator<Pair<JsonNode, String>> sorter = (p1, p2) -> {
        String t1 = p1.getLeft().get("term").asText();
        String t2 = p2.getLeft().get("term").asText();
        boolean t1Current = current(subject, medium, nwbibspatial, nwbibsubject, owner, t, field, t1, raw);
        boolean t2Current = current(subject, medium, nwbibspatial, nwbibsubject, owner, t, field, t2, raw);
        if (t1Current == t2Current) {
            if (!field.equals(ISSUED_FIELD)) {
                Integer c1 = p1.getLeft().get("count").asInt();
                Integer c2 = p2.getLeft().get("count").asInt();
                return c2.compareTo(c1);
            }
            String l1 = p1.getRight().substring(p1.getRight().lastIndexOf('>') + 1);
            String l2 = p2.getRight().substring(p2.getRight().lastIndexOf('>') + 1);
            return collator.compare(l1, l2);
        }
        return t1Current ? -1 : t2Current ? 1 : 0;
    };

    Function<Pair<JsonNode, String>, String> toHtml = pair -> {
        JsonNode json = pair.getLeft();
        String fullLabel = pair.getRight();
        String term = json.get("term").asText();
        if (field.equals(SUBJECT_LOCATION_FIELD)) {
            GeoPoint point = new GeoPoint(term);
            term = String.format("%s,%s", point.getLat(), point.getLon());
        }
        String mediumQuery = !field.equals(MEDIUM_FIELD) //
                ? medium
                : queryParam(medium, term);
        String typeQuery = !field.equals(TYPE_FIELD) //
                ? t
                : queryParam(t, term);
        String ownerQuery = !field.equals(ITEM_FIELD) //
                ? owner
                : withoutAndOperator(queryParam(owner, term));
        String nwbibsubjectQuery = !field.equals(NWBIB_SUBJECT_FIELD) //
                ? nwbibsubject
                : queryParam(nwbibsubject, term);
        String nwbibspatialQuery = !field.equals(NWBIB_SPATIAL_FIELD) //
                ? nwbibspatial
                : queryParam(nwbibspatial, term);
        String rawQuery = !field.equals(COVERAGE_FIELD) //
                ? raw
                : rawQueryParam(raw, term);
        String locationQuery = !field.equals(SUBJECT_LOCATION_FIELD) //
                ? location
                : term;
        String subjectQuery = !field.equals(SUBJECT_FIELD) //
                ? subject
                : queryParam(subject, term);
        String issuedQuery = !field.equals(ISSUED_FIELD) //
                ? issued
                : queryParam(issued, term);

        boolean current = current(subject, medium, nwbibspatial, nwbibsubject, owner, t, field, term, raw);

        String routeUrl = routes.Application.search(q, person, name, subjectQuery, id, publisher, issuedQuery,
                mediumQuery, nwbibspatialQuery, nwbibsubjectQuery, from, size, ownerQuery, typeQuery,
                sort(sort, nwbibspatialQuery, nwbibsubjectQuery, subjectQuery), false, set, locationQuery, word,
                corporation, rawQuery).url();

        String result = String.format(
                "<li " + (current ? "class=\"active\"" : "") + "><a class=\"%s-facet-link\" href='%s'>"
                        + "<input onclick=\"location.href='%s'\" class=\"facet-checkbox\" "
                        + "type=\"checkbox\" %s>&nbsp;%s</input>" + "</a></li>",
                Math.abs(field.hashCode()), routeUrl, routeUrl, current ? "checked" : "", fullLabel);

        return result;
    };

    Promise<Result> promise = Lobid.getFacets(q, person, name, subject, id, publisher, issued, medium,
            nwbibspatial, nwbibsubject, owner, field, t, set, location, word, corporation, raw).map(json -> {
                Stream<JsonNode> stream = StreamSupport.stream(
                        Spliterators.spliteratorUnknownSize(json.findValue("entries").elements(), 0), false);
                if (field.equals(ITEM_FIELD)) {
                    stream = preprocess(stream);
                }
                String labelKey = String.format(
                        "facets-labels.%s.%s.%s.%s.%s.%s.%s.%s.%s.%s.%s.%s.%s.%s.%s.%s.%s.%s.%s", field, raw, q,
                        person, name, id, publisher, set, word, corporation, subject, issued, medium,
                        nwbibspatial, nwbibsubject, raw, field.equals(ITEM_FIELD) ? "" : owner, t, location);

                @SuppressWarnings("unchecked")
                List<Pair<JsonNode, String>> labelledFacets = (List<Pair<JsonNode, String>>) Cache
                        .get(labelKey);
                if (labelledFacets == null) {
                    labelledFacets = stream.map(toLabel).filter(labelled).collect(Collectors.toList());
                    Cache.set(labelKey, labelledFacets, ONE_DAY);
                }
                return labelledFacets.stream().sorted(sorter).map(toHtml).collect(Collectors.toList());
            }).map(lis -> ok(String.join("\n", lis)));
    promise.onRedeem(r -> Cache.set(key, r, ONE_DAY));
    return promise;
}

From source file:org.cleverbus.api.entity.Message.java

/**
 * Gets the set of referenced funnel values.
 *
 * @return the set of referenced funnel values
 *///from  w w w  . j  a v a  2s . c o m
protected List<Funnel> getFunnels() {
    List<Funnel> result = new ArrayList<Funnel>(funnels);
    Collections.sort(result, new Comparator<Funnel>() {
        @Override
        public int compare(Funnel o1, Funnel o2) {
            return Collator.getInstance(LocaleContextHolder.getLocale()).compare(o1.getFunnelValue(),
                    o2.getFunnelValue());
        }
    });
    return result;
}

From source file:org.jahia.ajax.gwt.content.server.JahiaContentManagementServiceImpl.java

@Override
public PagingLoadResult<GWTJahiaNode> searchSQL(String searchString, int limit, int offset,
        List<String> nodeTypes, List<String> fields, boolean sortOnDisplayName)
        throws GWTJahiaServiceException {
    List<GWTJahiaNode> gwtJahiaNodes = search.searchSQL(searchString, limit, offset, nodeTypes, null, null,
            fields, retrieveCurrentSession());
    int total = gwtJahiaNodes.size();
    if (limit >= 0) {
        try {/*w w  w  .j a v  a  2s .  com*/
            Query q = retrieveCurrentSession().getWorkspace().getQueryManager().createQuery(searchString,
                    Query.JCR_SQL2);
            total = (int) q.execute().getNodes().getSize();
        } catch (RepositoryException e) {
            logger.error(e.getMessage(), e);
        }
    }
    if (sortOnDisplayName) {
        final Collator collator = Collator.getInstance(retrieveCurrentSession().getLocale());
        Collections.sort(gwtJahiaNodes, new Comparator<GWTJahiaNode>() {
            @Override
            public int compare(GWTJahiaNode o1, GWTJahiaNode o2) {
                return collator.compare(o1.getDisplayName(), o2.getDisplayName());
            }
        });
    }
    return new BasePagingLoadResult<GWTJahiaNode>(gwtJahiaNodes, offset, total);
}

From source file:com.redhat.rhn.common.localization.LocalizationService.java

/**
 * Returns a NEW instance of the collator/string comparator
 * based on the current locale..//from  w  ww . j av  a2  s.  c o m
 * Look at the javadoc for COllator to see what it does...
 * (basically an i18n aware string comparator)
 * @return neww instance of the collator
 */
public Collator newCollator() {
    Context context = Context.getCurrentContext();
    if (context != null && context.getLocale() != null) {
        return Collator.getInstance(context.getLocale());
    }
    return Collator.getInstance();
}

From source file:org.jahia.services.search.facets.SimpleJahiaJcrFacets.java

private NamedList<Object> sortValuesAfterChoiceListRenderer(NamedList<Object> values,
        ChoiceListRenderer renderer, ExtendedPropertyDefinition fieldPropertyType, Locale locale) {
    try {//from  ww w. j  ava2  s  .  c  o m
        //use case-insensitive and locale aware collator
        Collator collator = Collator.getInstance(locale);
        collator.setStrength(Collator.TERTIARY);
        Map<String, Integer> sortedLabels = new TreeMap<>(collator);
        int i = 0;
        boolean resolveReference = renderer instanceof NodeReferenceChoiceListRenderer ? true : false;
        JCRSessionWrapper currentUserSession = resolveReference
                ? JCRSessionFactory.getInstance().getCurrentUserSession(session.getWorkspace().getName(),
                        locale)
                : null;

        for (Map.Entry<String, Object> facetValueEntry : values) {
            String facetValueKey = facetValueEntry.getKey();
            sortedLabels.put(renderer.getStringRendering(locale, fieldPropertyType,
                    resolveReference
                            ? currentUserSession
                                    .getNode(StringUtils.substring(facetValueKey, facetValueKey.indexOf('/')))
                            : facetValueKey),
                    i++);
        }

        NamedList<Object> sortedValues = new NamedList<>();
        for (Integer index : sortedLabels.values()) {
            sortedValues.add(values.getName(index), values.getVal(index));
        }
        return sortedValues;
    } catch (RepositoryException | UnsupportedOperationException e) {
        logger.warn("Exception while sorting label rendered facet values, fallback to default sorting", e);
        return values;
    }
}

From source file:net.pms.dlna.RootFolder.java

private static boolean areNamesEqual(String aThis, String aThat) {
    Collator collator = Collator.getInstance(Locale.getDefault());
    collator.setStrength(Collator.PRIMARY);
    int comparison = collator.compare(aThis, aThat);
    return (comparison == 0);
}

From source file:org.apache.nifi.web.api.dto.DtoFactory.java

/**
 * Creates a ConnectionDTO from the specified Connection.
 *
 * @param connection connection//  w w w.ja va2s  .  co  m
 * @return dto
 */
public ConnectionDTO createConnectionDto(final Connection connection) {
    if (connection == null) {
        return null;
    }
    final ConnectionDTO dto = new ConnectionDTO();

    dto.setId(connection.getIdentifier());
    dto.setParentGroupId(connection.getProcessGroup().getIdentifier());

    final List<PositionDTO> bendPoints = new ArrayList<>();
    for (final Position bendPoint : connection.getBendPoints()) {
        bendPoints.add(createPositionDto(bendPoint));
    }
    dto.setBends(bendPoints);
    dto.setName(connection.getName());
    dto.setLabelIndex(connection.getLabelIndex());
    dto.setzIndex(connection.getZIndex());
    dto.setSource(createConnectableDto(connection.getSource()));
    dto.setDestination(createConnectableDto(connection.getDestination()));

    dto.setBackPressureObjectThreshold(connection.getFlowFileQueue().getBackPressureObjectThreshold());
    dto.setBackPressureDataSizeThreshold(connection.getFlowFileQueue().getBackPressureDataSizeThreshold());
    dto.setFlowFileExpiration(connection.getFlowFileQueue().getFlowFileExpiration());
    dto.setPrioritizers(new ArrayList<String>());
    for (final FlowFilePrioritizer comparator : connection.getFlowFileQueue().getPriorities()) {
        dto.getPrioritizers().add(comparator.getClass().getCanonicalName());
    }

    // For ports, we do not want to populate the relationships.
    for (final Relationship selectedRelationship : connection.getRelationships()) {
        if (!Relationship.ANONYMOUS.equals(selectedRelationship)) {
            if (dto.getSelectedRelationships() == null) {
                dto.setSelectedRelationships(new TreeSet<String>(Collator.getInstance(Locale.US)));
            }

            dto.getSelectedRelationships().add(selectedRelationship.getName());
        }
    }

    // For ports, we do not want to populate the relationships.
    for (final Relationship availableRelationship : connection.getSource().getRelationships()) {
        if (!Relationship.ANONYMOUS.equals(availableRelationship)) {
            if (dto.getAvailableRelationships() == null) {
                dto.setAvailableRelationships(new TreeSet<String>(Collator.getInstance(Locale.US)));
            }

            dto.getAvailableRelationships().add(availableRelationship.getName());
        }
    }

    return dto;
}