/** * 根据给定的条件,把 list 中的 javabean 排序。 * 用到了 commons beanutils 和 commons.collections * * @param list 待排序的 list * @param listOrderedMap 排序条件。 * 这是一个有序的 list ,排序条件按照加入到 list 的 bean 的属性(map 的 key)的先后顺序排序。 * listOrderedMap 的 key 为待排序的 bean 的属性名称,值为是否按该属性的正序排序,true 为正序,false 为逆序。 * 使用方法见本类的 testSortListBeans() 方法例子,使用时注意不要写错 bean 的属性名称。 * @param <T> list 中的 bean 类型 */ public static <T> void sortListBeans(List<T> list, ListOrderedMap listOrderedMap) { int num = listOrderedMap.size(); ArrayList sortFields = new ArrayList(); for (int i = 0; i < num; i++) { // System.out.println("key =" + listOrderedMap.get(i) + " , value=" + listOrderedMap.getValue(i)); Comparator comp = ComparableComparator.getInstance(); comp = ComparatorUtils.nullLowComparator(comp); //允许null if ((Boolean) listOrderedMap.getValue(i) == false) comp = ComparatorUtils.reversedComparator(comp); //逆序 Comparator cmp = new BeanComparator((String) listOrderedMap.get(i), comp); sortFields.add(cmp); } ComparatorChain multiSort = new ComparatorChain(sortFields); Collections.sort(list, multiSort); }
/** * This method returns a comparator to be used for comparing the contents of cells, that is * the compareTo method will be invoked w/ displaytag Cell objects * @param propClass * @return */ public static Comparator getAppropriateComparatorForPropertyClass(Class propClass) { // TODO, do we really need to create so many comparators (1 per each cell)? if (propClass == null) { return new NullCellComparator(); } else if (TypeUtils.isDecimalClass(propClass) || TypeUtils.isIntegralClass(propClass)) { return new NumericCellComparator(); } else if (TypeUtils.isTemporalClass(propClass)) { return new TemporalCellComparator(); } else if (String.class.equals(propClass)) { // StringCellComparator is smarter about nulls than String.CASE_INSENSITIVE_ORDER return new StringCellComparator(); } else { return ComparableComparator.getInstance(); } }
/** * This method returns a comparator to be used for comparing propertyValues (in String form) * @param propClass * @return */ public static Comparator getAppropriateValueComparatorForPropertyClass(Class propClass) { if (propClass == null) { return NullValueComparator.getInstance(); } else if (TypeUtils.isDecimalClass(propClass) || TypeUtils.isIntegralClass(propClass)) { return NumericValueComparator.getInstance(); } else if (TypeUtils.isTemporalClass(propClass)) { return TemporalValueComparator.getInstance(); } else if (String.class.equals(propClass)) { // StringCellComparator is smarter about nulls than String.CASE_INSENSITIVE_ORDER return StringValueComparator.getInstance(); } else { return ComparableComparator.getInstance(); } }
/** * Converts a collection of Recipients into a collection of WebFriendlyRecipients which can be displayed in the UI * @param recipients recipients to convert * @return a collection of WebFriendlyRecipients which can be displayed in the UI */ public static List<WebFriendlyRecipient> getWebFriendlyRecipients(Collection<Recipient> recipients) { Collection<WebFriendlyRecipient> newRecipients = new ArrayList<WebFriendlyRecipient>(recipients.size()); for (Recipient recipient : recipients) { newRecipients.add(new WebFriendlyRecipient(recipient)); } List<WebFriendlyRecipient> recipientList = new ArrayList<WebFriendlyRecipient>(newRecipients); Collections.sort(recipientList, new Comparator<WebFriendlyRecipient>() { Comparator<String> comp = new ComparableComparator(); @Override public int compare(WebFriendlyRecipient o1, WebFriendlyRecipient o2) { return comp.compare(o1.getDisplayName().trim().toLowerCase(), o2.getDisplayName().trim().toLowerCase()); } }); return recipientList; }
/** * This method will sort a passed Collection * * @param c The collection to sort * @param sortProperty The javabean property to sort the elements of the Collection by * @param reverseOrder Boolean indicating whether or not to reverse the order of the collection * @return A sorted List of the passed elements */ public static <T> List<T> sort(Collection<T> c, String sortProperty, Boolean reverseOrder) { if (StringUtils.isEmpty(sortProperty)) { throw new IllegalArgumentException("sortProperty = " + sortProperty); } // fail early if the passed collection is null if (c == null) { return null; } // fail early if the passed collection is empty if (c.size() == 0) { return Collections.emptyList(); } List<T> l = new ArrayList<T>(c); Comparator comp = new BeanComparator(sortProperty, new ComparableComparator()); Collections.sort(l, comp); if (reverseOrder) { Collections.reverse(l); } return l; }
public void testIterator() throws Exception { final File logPath = new File(tmpDir, "tmp.log"); VolatileGeneration<Integer, Long> volatileGeneration = new VolatileGeneration(logPath, new IntSerializer(), new LongSerializer(), new ComparableComparator()); int[] random = new int[1000000]; Random r = new Random(0); for (int i = 0; i < random.length; i++) { random[i] = r.nextInt(); } for (int element : random) { volatileGeneration.put(element, (long)element); } int[] sorted = new int[random.length]; System.arraycopy(random, 0, sorted, 0, random.length); Arrays.sort(sorted); verifyIterationOrder(volatileGeneration, sorted); volatileGeneration.close(); volatileGeneration = new VolatileGeneration<Integer, Long>(new File(tmpDir, "tmp2.log"), new IntSerializer(), new LongSerializer(), new ComparableComparator()); volatileGeneration.replayTransactionLog(logPath); verifyIterationOrder(volatileGeneration, sorted); }
@SuppressWarnings("unchecked") private static Sorter getSorter(int trimSize, AggregationFunction aggregationFunction, boolean isComparable) { // This will cover both MIN and MINMV boolean minOrder = aggregationFunction instanceof MinAggregationFunction; if (isComparable) { if (minOrder) { return new ComparableSorter(trimSize, Collections.reverseOrder()); } else { return new ComparableSorter(trimSize, new ComparableComparator()); } } else { // Reverse the comparator so that keys are ordered in descending order if (minOrder) { return new NonComparableSorter(trimSize, new ComparableComparator(), aggregationFunction); } else { return new NonComparableSorter(trimSize, Collections.reverseOrder(), aggregationFunction); } } }
@SuppressWarnings("unchecked") public static void sortByProperties(List<? extends Object> list, boolean isNullHigh, boolean isReversed, String... props) { if (CollectionUtils.isNotEmpty(list)) { Comparator<?> typeComp = ComparableComparator.getInstance(); if (isNullHigh) { typeComp = ComparatorUtils.nullHighComparator(typeComp); } else { typeComp = ComparatorUtils.nullLowComparator(typeComp); } if (isReversed) { typeComp = ComparatorUtils.reversedComparator(typeComp); } List<Object> sortCols = new ArrayList<Object>(); if (props != null) { for (String prop : props) { sortCols.add(new BeanComparator(prop, typeComp)); } } if (sortCols.size() > 0) { Comparator<Object> sortChain = new ComparatorChain(sortCols); Collections.sort(list, sortChain); } } }
/** * Constructs a PropertyComparator for comparing beans using the properties named in the given List. * * <p>Properties will be compared * in the order in which they are listed. Case will be ignored if ignoreCase is true.</p> * * @param propertyNames List of property names (as Strings) used to compare beans * @param ignoreCase if true, case will be ignored during String comparisons */ public BeanPropertyComparator(List propertyNames, boolean ignoreCase) { if (propertyNames == null) { throw new IllegalArgumentException("invalid (null) propertyNames list"); } if (propertyNames.size() == 0) { throw new IllegalArgumentException("invalid (empty) propertyNames list"); } this.propertyNames = Collections.unmodifiableList(propertyNames); this.ignoreCase = ignoreCase; if (ignoreCase) { this.stringComparator = String.CASE_INSENSITIVE_ORDER; } else { this.stringComparator = ComparableComparator.getInstance(); } this.booleanComparator = new Comparator() { public int compare(Object o1, Object o2) { int compared = 0; Boolean b1 = (Boolean) o1; Boolean b2 = (Boolean) o2; if (!b1.equals(b2)) { if (b1.equals(Boolean.FALSE)) { compared = -1; } else { compared = 1; } } return compared; } }; this.genericComparator = ComparableComparator.getInstance(); }
public int doStartTag() { if (drugOrders == null || drugOrders.isEmpty()) { log.error("ForEachDrugOrderTag skipping body due to drugOrders param being null or empty: " + drugOrders); return SKIP_BODY; } // First retrieve all encounters matching the passed concept id, if provided. // If not provided, return all encounters matchingDrugOrders = new ArrayList<DrugOrder>(); for (Iterator<DrugOrder> i = drugOrders.iterator(); i.hasNext();) { DrugOrder d = i.next(); if (d != null) { // TODO: eventually we might want to have criteria, but not yet matchingDrugOrders.add(d); } } log.debug("ForEachDrugOrderTag found " + matchingDrugOrders.size() + " drug orders"); // Next, sort the encounters if (StringUtils.isEmpty(sortBy)) { sortBy = defaultSortBy; } Comparator comp = new BeanComparator(sortBy, (descending ? new ReverseComparator(new ComparableComparator()) : new ComparableComparator())); try { Collections.sort(matchingDrugOrders, comp); } catch (ClassCastException cce) { log .error("ForEachDrugTag unable to compare the list of drug orders passed. Ensure they are compatible with Comparator used."); } // Return appropriate number of results if (matchingDrugOrders.isEmpty()) { return SKIP_BODY; } else { pageContext.setAttribute(var, matchingDrugOrders.get(count++)); return EVAL_BODY_BUFFERED; } }
@Override public int doStartTag() { if (visits == null || visits.isEmpty()) { log.debug("ForEachVisitTag skipping body due to 'visits' param = " + visits); return SKIP_BODY; } // First retrieve all visits matching the passed visit type id, if provided. // If not provided, return all visits matchingVisits = new ArrayList<Visit>(); for (Iterator<Visit> i = visits.iterator(); i.hasNext();) { Visit e = i.next(); if (type == null || e.getVisitType().getVisitTypeId().intValue() == type.intValue()) { matchingVisits.add(e); } } log.debug("ForEachVisitTag found " + matchingVisits.size() + " visits matching type = " + type); // Next, sort the visits if (StringUtils.isEmpty(sortBy)) { sortBy = "visitDatetime"; } Comparator comp = new BeanComparator(sortBy, (descending ? new ReverseComparator(new ComparableComparator()) : new ComparableComparator())); Collections.sort(matchingVisits, comp); // Return appropriate number of results if (matchingVisits.isEmpty()) { return SKIP_BODY; } else { pageContext.setAttribute(var, matchingVisits.get(count++)); return EVAL_BODY_BUFFERED; } }
public int doStartTag() { if (obs == null || obs.isEmpty()) { log.error("ForEachObsTag skipping body due to obs param = " + obs); return SKIP_BODY; } // First retrieve all observations matching the passed concept id, if provided. // If not provided, return all observations matchingObs = new ArrayList<Obs>(); for (Iterator<Obs> i = obs.iterator(); i.hasNext();) { Obs o = i.next(); if (conceptId == null || (o.getConcept() != null && o.getConcept().getConceptId().intValue() == conceptId.intValue())) { matchingObs.add(o); } } log.debug("ForEachObsTag found " + matchingObs.size() + " observations matching conceptId = " + conceptId); // Next, sort these observations if (StringUtils.isEmpty(sortBy)) { sortBy = "obsDatetime"; } Comparator comp = new BeanComparator(sortBy, (descending ? new ReverseComparator(new ComparableComparator()) : new ComparableComparator())); Collections.sort(matchingObs, comp); // Return appropriate number of results if (matchingObs.isEmpty()) { return SKIP_BODY; } else { pageContext.setAttribute(var, matchingObs.get(count++)); return EVAL_BODY_BUFFERED; } }
@Override public Object provide(Object source, Object currentValue) { AlumniMailSendToBean bean = (AlumniMailSendToBean) source; final List<Degree> degrees = new ArrayList<Degree>(bean.getDegreeType().getDegreeSet()); Collections.sort(degrees, new ComparableComparator()); return degrees; }
/** * Creates a bucket. * * @param valueClass the class of the bucket values * @param orderer bucket entries orderer * @param comparator the comparator to use for bucket sorting * @param order the order type, {@link BucketOrder#ASCENDING}, {@link BucketOrder#DESCENDING} or {@link BucketOrder#NONE} * @param totalPosition the position of the total bucket * @throws JRException */ public BucketDefinition(Class<?> valueClass, BucketOrderer orderer, Comparator<Object> comparator, BucketOrder order, CrosstabTotalPositionEnum totalPosition) throws JRException { this.orderer = orderer; this.order = order; if (orderer == null) { // we don't have a bucket orderer if (order == BucketOrder.NONE) { // no ordering, values are inserted in the order in which they come this.bucketValueComparator = null; } else { // the buckets are ordered using the bucket values // if there's no comparator, we're assuming that the values are Comparable this.bucketValueComparator = createOrderComparator(comparator, order); } } else { // we have an order by expression // we only need an internal ordering for bucket values if (Comparable.class.isAssignableFrom(valueClass)) { // using natural order this.bucketValueComparator = ComparableComparator.getInstance(); } else { // using an arbitrary rank comparator // TODO lucianc couldn't we just set here bucketValueComparator to null? if (log.isDebugEnabled()) { log.debug("Using arbitrary rank comparator for bucket"); } this.bucketValueComparator = new ArbitraryRankComparator(); } } this.totalPosition = totalPosition; computeTotal = totalPosition != CrosstabTotalPositionEnum.NONE || orderer != null; }
@Override public Comparator<TitanElement> getSortOrder() { if (orders.isEmpty()) return new ComparableComparator(); else return orders; }
@Override public T getStart() { Preconditions.checkArgument(!isEmpty(),"There are no points in this interval"); return (T)Collections.min(points,ComparableComparator.getInstance()); }
@Override public T getEnd() { Preconditions.checkArgument(!isEmpty(), "There are no points in this interval"); return (T)Collections.max(points,ComparableComparator.getInstance()); }
/** * Sets up the expected state by retrieving the selected RouteQueue by RouteQueueId, and placing it in the * ExistingRouteQueue member. * * Called by the super's Execute method on every request. */ @Override public ActionMessages establishRequiredState(HttpServletRequest request, ActionForm form) throws Exception { request.setAttribute("rice_constant", getServlet().getServletContext().getAttribute("RiceConstants")); request.setAttribute("ksb_constant", getServlet().getServletContext().getAttribute("KSBConstants")); MessageQueueForm routeQueueForm = (MessageQueueForm) form; routeQueueForm.setMyIpAddress(RiceUtilities.getIpNumber()); routeQueueForm.setMyApplicationId(CoreConfigHelper.getApplicationId()); routeQueueForm.setMessagePersistence(ConfigContext.getCurrentContextConfig().getProperty(KSBConstants.Config.MESSAGE_PERSISTENCE)); routeQueueForm.setMessageDelivery(ConfigContext.getCurrentContextConfig().getProperty(KSBConstants.Config.MESSAGE_DELIVERY)); routeQueueForm.setMessageOff(ConfigContext.getCurrentContextConfig().getProperty(KSBConstants.Config.MESSAGING_OFF)); List<ServiceInfo> services = KsbApiServiceLocator.getServiceRegistry().getAllOnlineServices(); if (routeQueueForm.getMessageId() != null) { PersistedMessageBO rq = getRouteQueueService().findByRouteQueueId(routeQueueForm.getMessageId()); if (rq != null) { routeQueueForm.setExistingQueueDate(RiceConstants.getDefaultDateFormat().format(new Date())); routeQueueForm.setMessageQueueFromDatabase(rq); // establish IP addresses where this message could safely be forwarded to String serviceName = rq.getServiceName(); for (ServiceInfo serviceInfo : services) { if (serviceInfo.getServiceName().equals(serviceName)) { routeQueueForm.getIpAddresses().add( new ConcreteKeyValue(serviceInfo.getServerIpAddress(), serviceInfo.getServerIpAddress())); } } } else { ActionMessages messages = new ActionMessages(); messages.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage( "messagequeue.RouteQueueService.queuedDocumentNotFound", routeQueueForm.getMessageId().toString())); return messages; } routeQueueForm.setMessageId(null); } else if (!"clear".equalsIgnoreCase(request.getParameter("methodToCall"))) { List<PersistedMessageBO> queueEntries = findRouteQueues(request, routeQueueForm, routeQueueForm.getMaxRows() + 1); if (queueEntries.size() > 0) { Collections.sort(queueEntries, new Comparator() { private Comparator comp = new ComparableComparator(); @Override public int compare(Object object1, Object object2) { if (object1 == null && object2 == null) { return 0; } else if (object1 == null) { return 1; } else if (object2 == null) { return -1; } Long id1 = ((PersistedMessageBO) object1).getRouteQueueId(); Long id2 = ((PersistedMessageBO) object2).getRouteQueueId(); try { return this.comp.compare(id1, id2); } catch (Exception e) { return 0; } } }); } routeQueueForm.setMessageQueueRows(queueEntries); } return null; }
/** * @see javax.servlet.jsp.tagext.BodyTagSupport#doStartTag() * @should sort encounters by encounterDatetime in descending order * @should pass for a patient with no encounters */ @SuppressWarnings( { "rawtypes", "unchecked" }) @Override public int doStartTag() { if (encounters == null || encounters.isEmpty()) { log.debug("ForEachEncounterTag skipping body due to 'encounters' param = " + encounters); return SKIP_BODY; } //First, sort the encounters if (StringUtils.isEmpty(sortBy)) { sortBy = "encounterDatetime"; } Comparator comp = new BeanComparator(sortBy, (descending ? new ReverseComparator(new ComparableComparator()) : new ComparableComparator())); Collections.sort((List) encounters, comp); // Next, retrieve all encounters matching the passed encounter type id, if provided. // If not provided, return all encounters matchingEncs = new ArrayList<Encounter>(); for (Iterator<Encounter> i = encounters.iterator(); i.hasNext();) { if (getNum() != null && getNum() <= matchingEncs.size()) { break; } Encounter e = i.next(); if (type == null || e.getEncounterType().getEncounterTypeId().intValue() == type.intValue()) { matchingEncs.add(e); } } log.debug("ForEachEncounterTag found " + matchingEncs.size() + " encounters matching type = " + type); // Return appropriate number of results if (matchingEncs.isEmpty()) { return SKIP_BODY; } else { pageContext.setAttribute("count", count); pageContext.setAttribute(var, matchingEncs.get(count++)); return EVAL_BODY_BUFFERED; } }
/** {@inheritDoc} */ @SuppressWarnings("unchecked") @Override public Comparator<Object> sortComparator() { return ComparableComparator.getInstance(); }
/** {@inheritDoc} */ @SuppressWarnings("unchecked") @Override public Comparator<Object> groupComparator() { return ComparableComparator.getInstance(); }
public Reader(Path path, Serializer<K> keySerializer, Serializer<V> valueSerializer, final boolean mlockFiles) throws IOException { this(path, new ComparableComparator(), keySerializer, valueSerializer, mlockFiles); }
/** * Constructs a property-based comparator for beans. * This constructor creates * a BeanComparator that uses the supplied Comparator to compare * the property values. * * @param property Name of a bean property, can contain the name * of a simple, nested, indexed, mapped, or combined * property. See {@link PropertyUtilsBean} for property query language * syntax. * @param comparator BeanComparator will pass the values of the * specified bean property to this Comparator. * If your bean property is not a comparable or * contains null values, a suitable comparator * may be supplied in this constructor. */ public BeanComparator( final String property, final Comparator<?> comparator ) { setProperty( property ); if (comparator != null) { this.comparator = comparator; } else { this.comparator = ComparableComparator.getInstance(); } }
/** * <p>Constructs a property-based comparator for beans. * This compares two beans by the property * specified in the property parameter. This constructor creates * a <code>BeanComparator</code> that uses a <code>ComparableComparator</code> * to compare the property values. * </p> * * <p>Passing "null" to this constructor will cause the BeanComparator * to compare objects based on natural order, that is * <code>java.lang.Comparable</code>. * </p> * * @param property String Name of a bean property, which may contain the * name of a simple, nested, indexed, mapped, or combined * property. See {@link PropertyUtilsBean} for property query language syntax. * If the property passed in is null then the actual objects will be compared */ public BeanComparator( final String property ) { this( property, ComparableComparator.getInstance() ); }