Example usage for java.util Collections reverse

List of usage examples for java.util Collections reverse

Introduction

In this page you can find the example usage for java.util Collections reverse.

Prototype

@SuppressWarnings({ "rawtypes", "unchecked" })
public static void reverse(List<?> list) 

Source Link

Document

Reverses the order of the elements in the specified list.

This method runs in linear time.

Usage

From source file:net.sourceforge.fenixedu.presentationTier.Action.publicRelationsOffice.AlumniInformationAction.java

public ActionForward manageRecipients(ActionMapping mapping, ActionForm actionForm, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    final Set<Sender> availableSenders = Sender.getAvailableSenders();
    Sender gepSender = getGEPSender(availableSenders);
    List<Recipient> recipients = new ArrayList<Recipient>();
    recipients.addAll(gepSender.getRecipientsSet());
    Collections.sort(recipients, new BeanComparator("toName"));
    Collections.reverse(recipients);
    request.setAttribute("recipients", recipients);
    return mapping.findForward("manageRecipients");
}

From source file:com.eucalyptus.tests.awssdk.S3ListMpuTests.java

@AfterMethod
public void cleanup() throws Exception {
    Collections.reverse(cleanupTasks);
    for (final Runnable cleanupTask : cleanupTasks) {
        try {/*  www .j av a  2s . c  o  m*/
            cleanupTask.run();
        } catch (Exception e) {
            print("Unable to run clean up task: " + e);
        }
    }
}

From source file:edu.depaul.armada.dao.ContainerLogDaoHibernate.java

/**
 * Returns a List<Metric> from all of the containers with state fields greater-than
 * or equal to certain user defined parameters.
 * @param memThreshold long// ww w .  j  a  v  a  2  s  . c om
 * @param cpuThreshold long
 * @param diskThreshold long
 * @param periodCountInHours int
 * @return List<Metric>
 */
@Override
public List<Metric> getStateCounts(long memThreshold, long cpuThreshold, long diskThreshold,
        int periodCountInHours) {
    List<Metric> metrics = new ArrayList<Metric>(periodCountInHours);
    Calendar cal = Calendar.getInstance();
    for (int i = 0; i < periodCountInHours; i++) {
        Date end = cal.getTime();
        int hour = cal.get(Calendar.HOUR_OF_DAY);
        cal.add(Calendar.HOUR_OF_DAY, -1);
        Date start = cal.getTime();

        Criteria criteria = newCriteria();
        criteria.add(Restrictions.le("timestamp", end));
        criteria.add(Restrictions.gt("timestamp", start)); // we don't want overlap here
        criteria.add(Restrictions.disjunction().add(Restrictions.ge("cpuUsed", cpuThreshold))
                .add(Restrictions.ge("memUsed", memThreshold)).add(Restrictions.ge("diskUsed", diskThreshold)));
        criteria.setProjection(Projections.countDistinct("container"));
        int count = ((Long) criteria.uniqueResult()).intValue();
        Metric temp = new Metric();
        temp.setHour(hour);
        temp.setValue(count);
        metrics.add(temp);
    }
    Collections.reverse(metrics); // we want the current time to be the last hour
    return metrics;
}

From source file:javazoom.jlgui.player.amp.visual.ui.SpectrumTimeAnalyzer.java

/**
 * Set visual colors from skin./*from   w w w  . jav a  2 s . co  m*/
 * @param viscolor
 */
public void setVisColor(String viscolor) {
    ArrayList visColors = new ArrayList();
    viscolor = viscolor.toLowerCase();
    ByteArrayInputStream in = new ByteArrayInputStream(viscolor.getBytes());
    BufferedReader bin = new BufferedReader(new InputStreamReader(in));
    try {
        String line = null;
        while ((line = bin.readLine()) != null) {
            visColors.add(getColor(line));
        }
        Color[] colors = new Color[visColors.size()];
        visColors.toArray(colors);
        Color[] specColors = new Color[15];
        System.arraycopy(colors, 2, specColors, 0, 15);
        List specList = Arrays.asList(specColors);
        Collections.reverse(specList);
        specColors = (Color[]) specList.toArray(specColors);
        setSpectrumAnalyserColors(specColors);
        setBackground((Color) visColors.get(0));
        if (visColors.size() > 23)
            setPeakColor((Color) visColors.get(23));
        if (visColors.size() > 18)
            setScopeColor((Color) visColors.get(18));
    } catch (IOException ex) {
        log.warn("Cannot parse viscolors", ex);
    } finally {
        try {
            if (bin != null)
                bin.close();
        } catch (IOException e) {
        }
    }
}

From source file:net.oddsoftware.android.feedscribe.data.FeedManager.java

public ArrayList<ShortFeedItem> getShortItems(long feedId) {
    ArrayList<ShortFeedItem> result = mDB.getShortFeedItems(feedId, null, false);

    if (result != null) {
        Collections.sort(result);
        Collections.reverse(result);
    }/*  ww w.j  ava2  s  . c  o m*/

    return result;
}

From source file:org.jasig.portlet.notice.service.rome.RomeNotificationService.java

private NotificationCategory fetchFromSource(final String url) {

    NotificationCategory rslt = null; // default

    XmlReader reader = null;/*from  ww  w .  j  a  v  a  2  s . c  o  m*/
    try {

        final URL u = new URL(url);

        reader = new XmlReader(u);
        final SyndFeedInput input = new SyndFeedInput();
        final SyndFeed feed = input.build(reader);

        rslt = new NotificationCategory();
        rslt.setTitle(feed.getTitle());

        final List<TimestampNotificationEntry> entries = new ArrayList<TimestampNotificationEntry>();

        @SuppressWarnings("unchecked")
        final List<SyndEntry> list = feed.getEntries();
        for (SyndEntry y : list) {

            if (log.isTraceEnabled()) {
                log.trace("Processing SyndEntry:  \n" + y.toString());
            }

            final long timestamp = y.getPublishedDate().getTime();
            final TimestampNotificationEntry entry = new TimestampNotificationEntry(timestamp);

            // Strongly-typed members
            entry.setSource(feed.getAuthor());
            entry.setTitle(y.getTitle());
            entry.setUrl(y.getLink());
            // No priority
            // No due date
            // No image

            // Body
            final StringBuilder body = new StringBuilder();
            final SyndContent desc = y.getDescription();
            if (desc != null) {
                // Prefer description
                body.append(desc.getValue());
            }
            if (body.length() == 0) {
                // Fall back to contents
                @SuppressWarnings("unchecked")
                final List<SyndContent> contents = y.getContents();
                for (SyndContent c : contents) {
                    body.append(c.getValue());
                }
            }
            if (body.length() == 0) {
                // Last resort... 
                body.append(NO_FURTHER_INFORMATION);
            }
            entry.setBody(body.toString());

            // Attributes -- TODO:  These labels should be internationalized in messages.properties
            final List<NotificationAttribute> attributes = new ArrayList<NotificationAttribute>();
            final String author = y.getAuthor();
            if (StringUtils.isNotBlank(author)) {
                attributes.add(new NotificationAttribute("Author", author));
            }
            final Date publishedDate = y.getPublishedDate();
            if (publishedDate != null) {
                attributes.add(new NotificationAttribute("Published date", DATE_FORMAT.format(publishedDate)));
            }
            final Date updatededDate = y.getUpdatedDate();
            if (updatededDate != null) {
                attributes.add(new NotificationAttribute("Updated date", DATE_FORMAT.format(updatededDate)));
            }
            entry.setAttributes(attributes);

            entries.add(entry);

        }

        // Items should be in reverse chronological order
        Collections.sort(entries);
        Collections.reverse(entries);

        rslt.setEntries(new ArrayList<NotificationEntry>(entries));

    } catch (Exception e) {
        final String msg = "Unable to read the specified feed:  " + url;
        log.error(msg, e);
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException ioe) {
                final String msg = "Unable to close the XmlReader";
                log.error(msg, ioe);
            }
        }
    }

    return rslt;

}

From source file:gobblin.writer.partitioner.TimeBasedWriterPartitioner.java

@SuppressWarnings("fallthrough")
private Schema getGranularityBasedSchema() {
    FieldAssembler<Schema> assembler = SchemaBuilder.record("GenericRecordTimePartition")
            .namespace("gobblin.writer.partitioner").fields();

    // Construct the fields in reverse order
    if (!Strings.isNullOrEmpty(this.writerPartitionSuffix)) {
        assembler = assembler.name(SUFFIX).type(Schema.create(Schema.Type.STRING)).noDefault();
    }//from  ww  w  .ja  va 2 s  . c o m
    assembler = assembler.name(this.granularity.toString()).type(Schema.create(Schema.Type.STRING)).noDefault();

    if (!Strings.isNullOrEmpty(this.writerPartitionPrefix)) {
        assembler = assembler.name(PREFIX).type(Schema.create(Schema.Type.STRING)).noDefault();
    }

    Schema schema = assembler.endRecord();
    Collections.reverse(schema.getFields());
    return schema;
}

From source file:de.digiway.rapidbreeze.server.infrastructure.objectstorage.ObjectStorage.java

/**
 * Loads all instances which apply to the given filter.
 *
 * @param <T>/*  w w w.java  2s. c om*/
 * @param filter
 * @return
 */
public <T> List<T> load(final ObjectStorageFilter filter) {
    List<T> list = load(filter.getClazz());

    // Apply order by filter criteria:
    if (filter.getOrderByProperty() != null) {
        Collections.sort(list, new Comparator<T>() {
            @Override
            public int compare(T o1, T o2) {
                Comparable value1 = ObjectStorageHelper.getProperty(o1, filter.getOrderByProperty());
                Comparable value2 = ObjectStorageHelper.getProperty(o2, filter.getOrderByProperty());
                return ObjectUtils.compare(value1, value2);
            }
        });
        if (!filter.isOrderByAscending()) {
            Collections.reverse(list);
        }
    }

    return list;
}

From source file:com.xpn.xwiki.stats.impl.xwiki.XWikiStatsReader.java

/**
 * Retrieves document statistics./*  w w w.ja v  a 2  s .c om*/
 * 
 * @param action the action the results should be ordered by. It can be one of: "view", "save" or "download". If the
 *            action is "view" then the documents are ordered by the number of times they have been viewed so far.
 * @param scope the set of documents for which to retrieve statistics.
 * @param period the period of time, including its start date but excluding its end date.
 * @param range the sub-range to return from the entire result set. Use this parameter for pagination.
 * @param context the XWiki context.
 * @return A list of DocumentStats objects
 */
public List<DocumentStats> getDocumentStatistics(String action, Scope scope, Period period, Range range,
        XWikiContext context) {
    List<DocumentStats> documentStatsList;

    List<Object> paramList = new ArrayList<Object>(4);

    String nameFilter = getHqlNameFilterFromScope(scope, paramList);

    String sortOrder = getHqlSortOrderFromRange(range);

    XWikiHibernateStore store = context.getWiki().getHibernateStore();

    try {
        String query = MessageFormat.format("select name, sum(pageViews) from DocumentStats"
                + " where {0} and action=? and ? <= period and period < ? group by name order"
                + " by sum(pageViews) {1}", nameFilter, sortOrder);

        paramList.add(action);
        paramList.add(period.getStartCode());
        paramList.add(period.getEndCode());

        List<?> solist = store.search(query, range.getAbsoluteSize(), range.getAbsoluteStart(), paramList,
                context);

        documentStatsList = getDocumentStatistics(solist, action);
        if (range.getSize() < 0) {
            Collections.reverse(documentStatsList);
        }
    } catch (XWikiException e) {
        documentStatsList = Collections.emptyList();
    }

    return documentStatsList;
}

From source file:acromusashi.stream.ml.anomaly.lof.LofCalculator.java

/**
 * ??<br>//  ww  w  .ja  v a 2s.  com
 * ?????????????{@link #initDataSet(int, LofDataSet)}???
 * 
 * @param baseDataSet ?
 * @param targetDataSet ?
 * @param max ??
 * @return ?
 */
public static LofDataSet mergeDataSet(LofDataSet baseDataSet, LofDataSet targetDataSet, int max) {
    Collection<LofPoint> basePointList = baseDataSet.getDataMap().values();
    Collection<LofPoint> targetPointList = targetDataSet.getDataMap().values();

    // LOF??????
    List<LofPoint> mergedList = new ArrayList<>();
    mergedList.addAll(basePointList);
    mergedList.addAll(targetPointList);
    Collections.sort(mergedList, new LofPointComparator());

    // ?????????
    Collections.reverse(mergedList);

    // ?????????
    // ??????????????ID??????
    // ??????ID?????????????????
    Set<String> registeredId = new HashSet<>();
    int addedCount = 0;
    LofDataSet resultDataSet = new LofDataSet();

    for (LofPoint targetPoint : mergedList) {
        if (registeredId.contains(targetPoint.getDataId()) == true) {
            continue;
        }

        registeredId.add(targetPoint.getDataId());
        resultDataSet.addData(targetPoint);
        addedCount++;

        if (addedCount >= max) {
            break;
        }
    }

    return resultDataSet;
}