List of usage examples for java.text Collator compare
@Override public int compare(Object o1, Object o2)
From source file:de.acosix.alfresco.site.hierarchy.repo.service.SiteHierarchyServiceImpl.java
/** * * {@inheritDoc}/*w ww .ja v a 2 s . c om*/ */ @Override public List<SiteInfo> listTopLevelSites(final boolean respectShowInHierarchyMode) { LOGGER.debug("Listing top level sites"); final SearchParameters sp = new SearchParameters(); sp.addStore(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE); sp.setQueryConsistency(QueryConsistency.TRANSACTIONAL_IF_POSSIBLE); sp.setLanguage(SearchService.LANGUAGE_FTS_ALFRESCO); final MessageFormat queryFormat = new MessageFormat("TYPE:\"{0}\" AND ASPECT:\"{1}\"", Locale.ENGLISH); String query = queryFormat.format(new Object[] { SiteModel.TYPE_SITE.toPrefixString(this.namespaceService), SiteHierarchyModel.ASPECT_TOP_LEVEL_SITE.toPrefixString(this.namespaceService) }); if (respectShowInHierarchyMode) { // this will cause db-fts not to be used final MessageFormat queryFilterFormat = new MessageFormat("={0}:{1} OR (={0}:{2} AND ASPECT:\"{3}\")", Locale.ENGLISH); final String queryFilter = queryFilterFormat.format(new Object[] { SiteHierarchyModel.PROP_SHOW_IN_HIERARCHY_MODE.toPrefixString(this.namespaceService), SiteHierarchyModel.CONSTRAINT_SHOW_IN_HIERARCHY_MODES_ALWAYS, SiteHierarchyModel.CONSTRAINT_SHOW_IN_HIERARCHY_MODES_IF_PARENT_OR_CHILD, SiteHierarchyModel.ASPECT_PARENT_SITE.toPrefixString(this.namespaceService) }); // if we did not want to support 5.0.d we could use filter query support // TODO find a way to dynamically use filter query support WITHOUT reflection query = query + " AND (" + queryFilter + ")"; } sp.setQuery(query); LOGGER.debug("Using FTS query \"{}\" to list top level sites", query); // we use short name sort since that is properly handled in either db-fts or fts // and might be specific enough so that in-memory post sort does not have to do that much final String shortNameSort = "@" + ContentModel.PROP_NAME.toPrefixString(this.namespaceService); sp.addSort(shortNameSort, true); List<SiteInfo> sites; final ResultSet resultSet = this.searchService.query(sp); try { sites = new ArrayList<>(resultSet.length()); resultSet.forEach(resultRow -> { final NodeRef nodeRef = resultRow.getNodeRef(); final SiteInfo site = this.siteService.getSite(nodeRef); if (site != null) { sites.add(site); } }); } finally { resultSet.close(); } final Collator collator = Collator.getInstance(I18NUtil.getLocale()); Collections.sort(sites, (siteA, siteB) -> { final int titleCompareResult = collator.compare(siteA.getTitle(), siteB.getTitle()); return titleCompareResult; }); LOGGER.debug("Listed top level sites {}", sites); return sites; }
From source file:com.evolveum.midpoint.web.component.prism.ContainerValueWrapper.java
private int compareByDisplayNames(ItemWrapper pw1, ItemWrapper pw2, Collator collator) { return collator.compare(pw1.getDisplayName(), pw2.getDisplayName()); }
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 w w . ja va 2s. 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'/> %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> %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:edu.cornell.mannlib.vitro.webapp.beans.VClassGroup.java
/** * Sorts VClassGroup objects by group rank, then alphanumeric. * @author bdc34 modified by jc55, bjl23 * @return a negative integer, zero, or a positive integer as the * first argument is less than, equal to, or greater than the * second. //from w ww. j ava 2 s.co m */ public int compareTo(VClassGroup o2) { Collator collator = Collator.getInstance(); if (o2 == null) { log.error("object NULL in DisplayComparator()"); return 0; } int diff = (this.getDisplayRank() - o2.getDisplayRank()); if (diff == 0) { //put null public name classgrups at end of list if (this.getPublicName() == null) { if (o2.getPublicName() == null) return 0; //or maybe collator.compare(this.getURI(),o2.getURI()) ??? else return 1; } else if (o2.getPublicName() == null) { return -1; } else { return collator.compare(this.getPublicName(), o2.getPublicName()); } } return diff; }
From source file:de.baumann.thema.RequestActivity.java
@SuppressWarnings("unchecked") private void prepareData() // Sort the apps { ArrayList<AppInfo> arrayList = new ArrayList(); PackageManager pm = getPackageManager(); Intent intent = new Intent("android.intent.action.MAIN", null); intent.addCategory("android.intent.category.LAUNCHER"); List list = pm.queryIntentActivities(intent, 0); Iterator localIterator = list.iterator(); if (DEBUG)/*from w w w. ja va 2s . c o m*/ Log.v(TAG, "list.size(): " + list.size()); for (int i = 0; i < list.size(); i++) { ResolveInfo resolveInfo = (ResolveInfo) localIterator.next(); // This is the main part where the already styled apps are sorted out. if ((list_activities .indexOf(resolveInfo.activityInfo.packageName + "/" + resolveInfo.activityInfo.name) == -1)) { AppInfo tempAppInfo = new AppInfo( resolveInfo.activityInfo.packageName + "/" + resolveInfo.activityInfo.name, //Get package/activity resolveInfo.loadLabel(pm).toString(), //Get the app name getHighResIcon(pm, resolveInfo) //Loads xxxhdpi icon, returns normal if it on fail //Unselect icon per default ); arrayList.add(tempAppInfo); // This is just for debugging if (DEBUG) Log.i(TAG, "Added app: " + resolveInfo.loadLabel(pm)); } else { // This is just for debugging if (DEBUG) Log.v(TAG, "Removed app: " + resolveInfo.loadLabel(pm)); } } Collections.sort(arrayList, new Comparator<AppInfo>() { //Custom comparator to ensure correct sorting for characters like and apps starting with a small letter like iNex @Override public int compare(AppInfo object1, AppInfo object2) { Locale locale = Locale.getDefault(); Collator collator = Collator.getInstance(locale); collator.setStrength(Collator.TERTIARY); if (DEBUG) Log.v(TAG, "Comparing \"" + object1.getName() + "\" to \"" + object2.getName() + "\""); return collator.compare(object1.getName(), object2.getName()); } }); list_activities_final = arrayList; }
From source file:org.alfresco.rest.api.impl.SitesImpl.java
private PagingResults<SiteInfo> getFavouriteSites(String userName, PagingRequest pagingRequest) { final Collator collator = Collator.getInstance(); final Set<SiteInfo> sortedFavouriteSites = new TreeSet<SiteInfo>(new Comparator<SiteInfo>() { @Override//from ww w . ja v a 2 s . com public int compare(SiteInfo o1, SiteInfo o2) { return collator.compare(o1.getTitle(), o2.getTitle()); } }); Map<String, Serializable> prefs = preferenceService.getPreferences(userName, FAVOURITE_SITES_PREFIX); for (Entry<String, Serializable> entry : prefs.entrySet()) { boolean isFavourite = false; Serializable s = entry.getValue(); if (s instanceof Boolean) { isFavourite = (Boolean) s; } if (isFavourite) { String siteShortName = entry.getKey().substring(FAVOURITE_SITES_PREFIX_LENGTH) .replace(".favourited", ""); SiteInfo siteInfo = siteService.getSite(siteShortName); if (siteInfo != null) { sortedFavouriteSites.add(siteInfo); } } } int totalSize = sortedFavouriteSites.size(); final PageDetails pageDetails = PageDetails.getPageDetails(pagingRequest, totalSize); final List<SiteInfo> page = new ArrayList<SiteInfo>(pageDetails.getPageSize()); Iterator<SiteInfo> it = sortedFavouriteSites.iterator(); for (int counter = 0; counter < pageDetails.getEnd() && it.hasNext(); counter++) { SiteInfo favouriteSite = it.next(); if (counter < pageDetails.getSkipCount()) { continue; } if (counter > pageDetails.getEnd() - 1) { break; } page.add(favouriteSite); } return new PagingResults<SiteInfo>() { @Override public List<SiteInfo> getPage() { return page; } @Override public boolean hasMoreItems() { return pageDetails.hasMoreItems(); } @Override public Pair<Integer, Integer> getTotalResultCount() { Integer total = Integer.valueOf(sortedFavouriteSites.size()); return new Pair<Integer, Integer>(total, total); } @Override public String getQueryExecutionId() { return null; } }; }
From source file:org.apache.ddlutils.model.Table.java
/** * Sorts the foreign keys alphabetically. * /* ww w .j a va 2 s .com*/ * @param caseSensitive Whether case matters */ public void sortForeignKeys(final boolean caseSensitive) { if (!_foreignKeys.isEmpty()) { final Collator collator = Collator.getInstance(); Collections.sort(_foreignKeys, new Comparator() { public int compare(Object obj1, Object obj2) { String fk1Name = ((ForeignKey) obj1).getName(); String fk2Name = ((ForeignKey) obj2).getName(); if (!caseSensitive) { fk1Name = (fk1Name != null ? fk1Name.toLowerCase() : null); fk2Name = (fk2Name != null ? fk2Name.toLowerCase() : null); } return collator.compare(fk1Name, fk2Name); } }); } }
From source file:org.apache.ddlutils.platform.JdbcModelReader.java
/** * Reads the tables from the database metadata. * //from w w w . jav a 2 s. c o m * @param catalog The catalog to acess in the database; use <code>null</code> for the default value * @param schemaPattern The schema(s) to acess in the database; use <code>null</code> for the default value * @param tableTypes The table types to process; use <code>null</code> or an empty list for the default ones * @return The tables */ protected Collection readTables(String catalog, String schemaPattern, String[] tableTypes) throws SQLException { ResultSet tableData = null; try { DatabaseMetaDataWrapper metaData = new DatabaseMetaDataWrapper(); metaData.setMetaData(_connection.getMetaData()); metaData.setCatalog(catalog == null ? getDefaultCatalogPattern() : catalog); metaData.setSchemaPattern(schemaPattern == null ? getDefaultSchemaPattern() : schemaPattern); metaData.setTableTypes( (tableTypes == null) || (tableTypes.length == 0) ? getDefaultTableTypes() : tableTypes); tableData = metaData.getTables(getDefaultTablePattern()); List tables = new ArrayList(); while (tableData.next()) { Map values = readColumns(tableData, getColumnsForTable()); Table table = readTable(metaData, values); if (table != null) { tables.add(table); } } final Collator collator = Collator.getInstance(); Collections.sort(tables, new Comparator() { public int compare(Object obj1, Object obj2) { return collator.compare(((Table) obj1).getName().toUpperCase(), ((Table) obj2).getName().toUpperCase()); } }); return tables; } finally { closeResultSet(tableData); } }
From source file:com.microsoft.tfs.client.eclipse.sync.SynchronizeSubscriber.java
/** * Given a list of paths, this will remove any duplicates. It uses a * Collator to detect duplicates for Unicode safety. * * @param paths//from w ww . j a v a2 s.c om * List of paths to uniqueify * @return List of unique paths specified */ private List<String> getUniquePaths(final List<String> paths) { final Collator collator = Collator.getInstance(Locale.US); final ArrayList<String> uniquePaths = new ArrayList<String>(); for (final String givenPath : paths) { boolean duplicate = false; for (final String existingPath : uniquePaths) { if (collator.compare(givenPath, existingPath) == 0) { duplicate = true; break; } } if (!duplicate) { uniquePaths.add(givenPath); } } return uniquePaths; }
From source file:org.uguess.android.sysinfo.NetStateManager.java
void refresh() { ArrayList<ConnectionItem> data = new ArrayList<ConnectionItem>(); data.add(dummyInfo);// w w w .jav a2 s .c o m ArrayList<ConnectionItem> items = readStatesRaw(); if (items != null) { final int type = Util.getIntOption(getActivity(), PSTORE_NETMANAGER, PREF_KEY_SORT_ORDER_TYPE, ORDER_TYPE_PROTO); final int direction = Util.getIntOption(getActivity(), PSTORE_NETMANAGER, PREF_KEY_SORT_DIRECTION, ORDER_ASC); final Collator clt = Collator.getInstance(); switch (type) { case ORDER_TYPE_PROTO: Collections.sort(items, new Comparator<ConnectionItem>() { public int compare(ConnectionItem obj1, ConnectionItem obj2) { return clt.compare(obj1.proto, obj2.proto) * direction; } }); break; case ORDER_TYPE_LOCAL: Collections.sort(items, new Comparator<ConnectionItem>() { public int compare(ConnectionItem obj1, ConnectionItem obj2) { return clt.compare(obj1.local, obj2.local) * direction; } }); break; case ORDER_TYPE_REMOTE: Collections.sort(items, new Comparator<ConnectionItem>() { public int compare(ConnectionItem obj1, ConnectionItem obj2) { return clt.compare(obj1.remoteName == null ? obj1.remote : obj1.remoteName, obj2.remoteName == null ? obj2.remote : obj2.remoteName) * direction; } }); break; case ORDER_TYPE_STATE: Collections.sort(items, new Comparator<ConnectionItem>() { public int compare(ConnectionItem obj1, ConnectionItem obj2) { return clt.compare(obj1.state == null ? "" //$NON-NLS-1$ : obj1.state, obj2.state == null ? "" //$NON-NLS-1$ : obj2.state) * direction; } }); break; } data.addAll(items); } ArrayAdapter<ConnectionItem> adapter = (ArrayAdapter<ConnectionItem>) getListView().getAdapter(); adapter.setNotifyOnChange(false); adapter.clear(); for (int i = 0, size = data.size(); i < size; i++) { adapter.add(data.get(i)); } adapter.notifyDataSetChanged(); if (adapter.getCount() == 1) { Log.d(NetStateManager.class.getName(), "No network traffic detected"); //$NON-NLS-1$ } }