public static String highlight(String text, String[] words) { if (text == null) { return null; } if (words == null || words.length == 0) { return text; } // TODO Consider using a primitive array List<Pair<Integer, Integer>> positions = Lists.newArrayList(); String lower = text.toLowerCase(); for (int i = 0; i < words.length; i++) { String word = words[i].toLowerCase(); int start = 0; while (start != -1) { start = lower.indexOf(word, start); if (start != -1) { int end = start + word.length(); positions.add(Pair.of(start, end)); start++; } } } if (positions.isEmpty()) { return text; } Collections.sort( positions, new Comparator<Pair<Integer, Integer>>() { @Override public int compare(Pair<Integer, Integer> o1, Pair<Integer, Integer> o2) { int comparison = o1.getKey().compareTo(o2.getKey()); if (comparison == 0) { return o2.getValue().compareTo(o1.getValue()); } return comparison; } }); StringBuilder out = new StringBuilder(); int pos = 0; for (Pair<Integer, Integer> position : positions) { int from = position.getKey(); int to = position.getValue(); if (from >= pos) { String sub = text.substring(pos, from); out.append(StringEscapeUtils.escapeXml(sub)); out.append("<em>"); out.append(StringEscapeUtils.escapeXml(text.substring(from, to))); out.append("</em>"); pos = to; } } out.append(text.substring(pos)); return out.toString(); }
public List<Item> getUsers() { PairSearchResult<User, Person> result = modelService.searchPairs(new UserQuery()); List<Item> list = Lists.newArrayList(); for (Pair<User, Person> pair : result.getList()) { Item item = new Item(); User user = pair.getKey(); item.user = user; item.person = pair.getValue(); item.userCanModifyPerson = securityService.canModify(item.person, user); item.setPublicCanViewPerson(securityService.canView(user, securityService.getPublicUser())); list.add(item); } return list; }