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:de.dhke.projects.cutil.collections.tree.DecisionTree.java

@Override
public List<? extends Node<Data>> getPath(final Node<Data> node) {
    final List<Node<Data>> path = new ArrayList<>();

    for (Node<Data> currentNode = node; currentNode != null; currentNode = currentNode.getParent())
        path.add(currentNode);//from   w w w  .ja va2  s  . c o  m

    Collections.reverse(path);

    return path;
}

From source file:annis.visualizers.htmlvis.HTMLVis.java

private String createHTML(SDocumentGraph graph, VisualizationDefinition[] definitions) {
    SortedMap<Long, SortedSet<OutputItem>> outputStartTags = new TreeMap<Long, SortedSet<OutputItem>>();
    SortedMap<Long, SortedSet<OutputItem>> outputEndTags = new TreeMap<Long, SortedSet<OutputItem>>();
    StringBuilder sb = new StringBuilder();

    EList<SToken> token = graph.getSortedSTokenByText();

    for (SToken t : token) {

        for (VisualizationDefinition vis : definitions) {
            String matched = vis.getMatcher().matchedAnnotation(t);
            if (matched != null) {
                vis.getOutputter().outputHTML(t, matched, outputStartTags, outputEndTags);
            }/*from   w  w  w  .j  av a2  s  . c o m*/
        }
    }

    List<SSpan> spans = graph.getSSpans();
    for (VisualizationDefinition vis : definitions) {
        for (SSpan span : spans) {
            String matched = vis.getMatcher().matchedAnnotation(span);
            if (matched != null) {
                vis.getOutputter().outputHTML(span, matched, outputStartTags, outputEndTags);
            }
        }
    }

    // get all used indexes
    Set<Long> indexes = new TreeSet<Long>();
    indexes.addAll(outputStartTags.keySet());
    indexes.addAll(outputEndTags.keySet());

    for (Long i : indexes) {
        // output all strings belonging to this token position

        // first the start tags for this position
        SortedSet<OutputItem> itemsStart = outputStartTags.get(i);
        if (itemsStart != null) {
            Iterator<OutputItem> it = itemsStart.iterator();
            boolean first = true;
            while (it.hasNext()) {
                OutputItem s = it.next();
                if (!first) {
                    sb.append("-->");
                }
                first = false;
                sb.append(s.getOutputString());
                if (it.hasNext()) {
                    sb.append("<!--\n");
                }
            }
        }
        // then the end tags for this position, but inverse their order
        SortedSet<OutputItem> itemsEnd = outputEndTags.get(i);
        if (itemsEnd != null) {
            List<OutputItem> itemsEndReverse = new LinkedList<OutputItem>(itemsEnd);
            Collections.reverse(itemsEndReverse);
            for (OutputItem s : itemsEndReverse) {
                sb.append(s.getOutputString());
            }
        }

    }

    return sb.toString();
}

From source file:org.jdal.swing.ListTableModel.java

/** 
 * Initialize table. Load propertyDescriptors based on columNames or 
 * model introspection. /*from  w ww .j a va  2s  .c  o  m*/
 */
// FIXME: PropertyDescriptors  are now unused, review to remove.
public void init() {
    if (modelClass == null) {
        log.warn("Cannot initilize without  modelClass, set a list of models o specify a model class");
        return;
    }

    columnCount = 0;

    if (usingIntrospection) {
        pds = Arrays.asList(BeanUtils.getPropertyDescriptors(modelClass));
        Collections.reverse(pds);
        columnNames = new ArrayList<String>(pds.size());
        displayNames = new ArrayList<String>(pds.size());

        for (PropertyDescriptor propertyDescriptor : pds) {
            columnNames.add(propertyDescriptor.getName());
            displayNames.add(propertyDescriptor.getDisplayName());
        }
    }

    else {
        pds = new ArrayList<PropertyDescriptor>(columnNames.size());
        for (String name : columnNames) {
            PropertyDescriptor pd = PropertyUtils.getPropertyDescriptor(modelClass, name);
            if (pd == null)
                throw new RuntimeException(
                        "Invalid property [" + name + "]" + " for model class [" + modelClass.getName() + "]");
            pds.add(pd);
        }
    }

    columnCount += pds.size();

    if (usingChecks) {
        columnCount++;
        buildCheckArray();
    }

    if (usingActions) {
        columnCount += actions.size();
    }
}

From source file:com.github.matthesrieke.realty.CrawlerServlet.java

private String createGroupedItemsMarkup() {
    Map<DateTime, List<Ad>> items;
    StringBuilder sb = new StringBuilder();
    try {/*from   ww  w .ja  v  a2  s.c o  m*/
        items = this.storage.getItemsGroupedByDate();
    } catch (IOException e) {
        logger.warn("Retrieval of items failed.", e);
        sb.append("Retrieval of items failed.");
        sb.append(e);
        return sb.toString();
    }

    List<DateTime> sortedKeys = new ArrayList<DateTime>(items.keySet());
    Collections.sort(sortedKeys);
    Collections.reverse(sortedKeys);
    for (DateTime a : sortedKeys) {
        StringBuilder adsBuilder = new StringBuilder();
        List<Ad> ads = items.get(a);
        for (Ad ad : ads) {
            adsBuilder.append(ad.toHTML());
        }
        sb.append(this.groupTemplate.toString().replace("${GROUP_DATE}", a.toString(Util.GER_DATE_FORMAT))
                .replace("${entries}", adsBuilder.toString()));
    }

    return sb.toString();
}

From source file:de.tudarmstadt.ukp.dkpro.lexsemresource.graph.EntityGraphJUNG.java

/**
 * HITS with priors. Query-specific!// w w w.  j av  a2 s .c o m
 */
public List<String> getHITSWithPriors(Transformer<Entity, HITS.Scores> priors) {

    logger.info("Getting HITS with priors...");
    HITSWithPriors<Entity, EntityGraphEdge> ranker = new HITSWithPriors<Entity, EntityGraphEdge>(directedGraph,
            priors, 0.3);
    logger.info("Ranker was created.");
    logger.info("Evaluating...");
    ranker.evaluate();
    // ranker.printRankings(true, true);

    logger.info("Got HITS with priors.");
    Collection<Entity> vertices = directedGraph.getVertices();
    List<String> rankingList = new ArrayList<String>();
    Format formatter = new Format("%7.6f");

    for (Entity vertex : vertices) {
        rankingList.add("hub=" + formatter.format(ranker.getVertexScore(vertex).hub) + " authority="
                + formatter.format(ranker.getVertexScore(vertex).authority) + " " + vertex);
        // logger.info("HITS with priors ranking for " +
        // vertex.getVertexEntity() + " : " + ranker.getRankScore(vertex));
    }

    Collections.sort(rankingList);
    Collections.reverse(rankingList);
    // logger.info("Sorted PageRankings: " + rankingList);
    // ranker.printRankings(false, true);

    return rankingList;
}

From source file:com.logsniffer.web.controller.source.LogEntriesRestController.java

@RequestMapping(value = "/sources/randomAccessEntries", method = RequestMethod.POST)
@ResponseBody//from   www .j a v a  2  s  . c o m
LogEntriesResult getRandomAccessEntries(
        @Valid @RequestBody final LogSource<LogRawAccess<? extends LogInputStream>> activeLogSource,
        @RequestParam("log") final String logPath,
        @RequestParam(value = "navType", defaultValue = "BYTE") final NavigationType navType,
        @RequestParam(value = "mark") final String position, @RequestParam(value = "count") final int count)
        throws IOException, FormatException, ResourceNotFoundException {
    logger.debug("Start loading random access entries log={} from source={}, navType={}, position={}, count={}",
            logPath, activeLogSource, navType, position, count);
    try {
        final Log log = getLog(activeLogSource, logPath);
        final LogRawAccess<? extends LogInputStream> logAccess = activeLogSource.getLogAccess(log);
        LogPointer pointer = null;
        if (StringUtils.isNotEmpty(position)) {
            pointer = getResolver(navType).navigate(activeLogSource, logAccess, log, position).get();
        }
        final BufferedConsumer bc = new BufferedConsumer(count + 1);
        if (pointer != null) {
            if (pointer.isEOF()) {
                // End pointer, return the last 10 simply
                final BufferedConsumer bcLast = new BufferedConsumer(10);
                activeLogSource.getReader().readEntriesReverse(log, logAccess, pointer, bcLast);
                final List<LogEntry> readEntries = bcLast.getBuffer();
                Collections.reverse(readEntries);
                return new LogEntriesResult(activeLogSource.getReader().getFieldTypes(), readEntries,
                        getHighlightEntryIndex(pointer, -10, readEntries));
            }
        }
        activeLogSource.getReader().readEntries(log, logAccess, pointer != null ? pointer : null, bc);
        final List<LogEntry> entries = bc.getBuffer();
        if (entries.size() > 0) {
            final LogEntry first = entries.get(0);
            final LogEntry last = entries.get(entries.size() - 1);
            if (!first.getStartOffset().isSOF() && last.getEndOffset().isEOF() && entries.size() < 10) {
                // Hm, EOF reached
                final BufferedConsumer bcLast = new BufferedConsumer(10);
                activeLogSource.getReader().readEntriesReverse(log, logAccess, last.getEndOffset(), bcLast);
                final List<LogEntry> readEntries = bcLast.getBuffer();
                Collections.reverse(readEntries);
                return new LogEntriesResult(activeLogSource.getReader().getFieldTypes(), readEntries, -1);
            } else if (!first.isUnformatted()) {
                // -1 without effect, return from beginning
                return new LogEntriesResult(activeLogSource.getReader().getFieldTypes(), entries,
                        getHighlightEntryIndex(pointer, 0, entries));
            } else {
                // Return from the second one
                return new LogEntriesResult(activeLogSource.getReader().getFieldTypes(),
                        entries.subList(1, entries.size()), getHighlightEntryIndex(pointer, 0, entries) - 1);
            }
        } else {
            return new LogEntriesResult(activeLogSource.getReader().getFieldTypes(), entries, -1);
        }
    } finally {
        logger.debug("Finished loading random access entries from log={} and source={}", logPath,
                activeLogSource);
    }
}

From source file:edu.purdue.cybercenter.dm.service.TermService.java

@CacheEvict(value = "vocabulary", allEntries = true)
public edu.purdue.cybercenter.dm.domain.Term changeStatus(edu.purdue.cybercenter.dm.domain.Term dbTerm,
        EnumAssetStatus status) {// w ww . j av a2 s .c o m
    if (dbTerm == null) {
        return null;
    }

    // if status is defined use it; otherwise flip the status of the term
    Integer newStatus;
    if (status != null) {
        newStatus = status.getIndex();
    } else {
        Integer currentStatus = dbTerm.getStatusId();
        if (currentStatus == 1) {
            newStatus = 0;
        } else {
            newStatus = 1;
        }
    }

    edu.purdue.cybercenter.dm.domain.Term updatedTermplate;
    UUID uuid = dbTerm.getUuid();
    if (newStatus == 1) {
        // restore: only the tip
        edu.purdue.cybercenter.dm.domain.Term dbt = findByUuidAndVersionNumber(uuid, null);
        dbt.setStatusId(EnumAssetStatus.Operational.getIndex());
        updatedTermplate = domainObjectService.merge(dbt, edu.purdue.cybercenter.dm.domain.Term.class);
    } else {
        // deprecate: all  versions
        TypedQuery<edu.purdue.cybercenter.dm.domain.Term> query = DomainObjectHelper
                .createNamedQuery("Term.findByUuid", edu.purdue.cybercenter.dm.domain.Term.class);
        query.setParameter("uuid", uuid);
        List<edu.purdue.cybercenter.dm.domain.Term> templates = domainObjectService
                .executeTypedQueryWithResultList(query);
        // to keep the relative oreder of timeUpdated
        Collections.reverse(templates);
        for (edu.purdue.cybercenter.dm.domain.Term v : templates) {
            v.setStatusId(newStatus);
            domainObjectService.flush(v, edu.purdue.cybercenter.dm.domain.Term.class);
        }
        updatedTermplate = templates.get(0);
    }

    return updatedTermplate;
}

From source file:com.feilong.taglib.display.breadcrumb.BreadCrumbUtil.java

/**
 * ?? list./*from  www. j  a va  2  s  .c  om*/
 *
 * @param <T>
 *            the generic type
 * @param currentBreadCrumbEntity
 *            the current bread crumb entity
 * @param breadCrumbEntityList
 *            the bread crumb entity list
 * @return the all parent bread crumb entity list
 */
private static <T> List<BreadCrumbEntity<T>> sortOutAllParentBreadCrumbEntityList(
        BreadCrumbEntity<T> currentBreadCrumbEntity, List<BreadCrumbEntity<T>> breadCrumbEntityList) {
    if (null == currentBreadCrumbEntity) {
        //? , ????
        //TODO ??
        return breadCrumbEntityList;
    }
    // ??
    List<BreadCrumbEntity<T>> allParentBreadCrumbEntityList = new ArrayList<BreadCrumbEntity<T>>();
    allParentBreadCrumbEntityList = constructParentBreadCrumbEntityList(currentBreadCrumbEntity,
            breadCrumbEntityList, allParentBreadCrumbEntityList);

    LOGGER.info("before Collections.reverse,allParentBreadCrumbEntityList size:{}",
            allParentBreadCrumbEntityList.size());
    // ??
    Collections.reverse(allParentBreadCrumbEntityList);
    return allParentBreadCrumbEntityList;
}

From source file:com.idylwood.yahoo.YahooFinance.java

private DivSplitTable DownloadHistoricalDivSplits(String symbol) throws IOException {
    String csv = new HistoricalUrlBuilder(symbol).setType(HistoricalUrlBuilder.Type.DIVIDEND).download();
    String[] lines = csv.split("\n");

    final DivSplitTable ret = new DivSplitTable(lines.length);
    ret.symbol = symbol;//from  w w w  .  j  a  v a2 s  .  c  o m
    ret.dateAccessed = System.currentTimeMillis();

    for (String s : lines) {
        s = s.replaceAll(" ", "");
        String[] elements = s.split(",");
        if (elements[0].equals("DIVIDEND")) {
            Pair p = new Pair();
            int date = Integer.parseInt(elements[1]);
            p.date = new Date(date);
            p.second = 0;
            p.first = Double.parseDouble(elements[2]);
            ret.add(p);
        }
        if (elements[0].equals("SPLIT")) {
            Pair p = new Pair();
            int date = Integer.parseInt(elements[1]);
            p.date = new Date(date);
            p.first = 0;
            String[] fractionParts = elements[2].split(":"); // gonna be like 1:10 or something
            p.second = Double.parseDouble(fractionParts[1]) / Double.parseDouble(fractionParts[0]);
            ret.add(p);
        }
        if (elements[0].equals("STARTDATE"))
            ret.startDate = new Date(Integer.parseInt(elements[1]));
        if (elements[0].equals("ENDDATE"))
            ret.endDate = new Date(Integer.parseInt(elements[1]));
        if (elements[0].equals("STATUS"))
            ret.status = Integer.parseInt(elements[1]);
        if (elements[0].equals("TOTALSIZE"))
            ret.totalSize = Integer.parseInt(elements[1]);
    }

    //if (ret.totalSize != ret.data.size()) throw new RuntimeException("Uh oh");
    // TODO figure out what ret.totalSize represents

    Collections.reverse(ret); // ascending order

    return ret;
}

From source file:org.kuali.mobility.sakai.service.SakaiSiteServiceImpl.java

@SuppressWarnings("unchecked")
public Home findSakaiHome(String user, String shortDate) {
    try {//from   ww  w  .  j a  va2s  .c o m
        String url = configParamService.findValueByName("Sakai.Url.Base") + "user_prefs.json";
        ResponseEntity<InputStream> is = oncourseOAuthService.oAuthGetRequest(user, url, "text/html");
        String prefsJson = IOUtils.toString(is.getBody(), "UTF-8");
        Set<String> visibleSiteIds = new HashSet<String>();
        try {
            JSONObject jsonObj = (JSONObject) JSONSerializer.toJSON(prefsJson);
            JSONArray itemArray = jsonObj.getJSONArray("user_prefs_collection");
            if (itemArray != null) {
                for (Iterator<JSONObject> iter = itemArray.iterator(); iter.hasNext();) {
                    JSONObject object = iter.next();
                    visibleSiteIds.add(object.getString("siteId"));
                }
            }
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
        }

        Set<String> calendarCourseIds = new HashSet<String>();
        try {
            Calendar todayDate = Calendar.getInstance();
            Calendar tomorrowDate = Calendar.getInstance();
            if (shortDate != null) {
                try {
                    todayDate.setTime(Constants.DateFormat.queryStringDateFormat.getFormat().parse(shortDate));
                } catch (Exception e) {
                }
            }
            todayDate.set(Calendar.HOUR, 0);
            todayDate.set(Calendar.MINUTE, 0);
            todayDate.set(Calendar.SECOND, 0);
            todayDate.set(Calendar.MILLISECOND, 0);
            tomorrowDate.setTime(todayDate.getTime());
            tomorrowDate.add(Calendar.DATE, 1);
            ListViewEvents listViewEvents = calendarEventOAuthService.retrieveViewEventsList(user,
                    todayDate.getTime(), todayDate.getTime(), todayDate.getTime(), null);
            List<ListData> events = listViewEvents.getEvents();
            if (events.size() > 0) {
                ListData list = events.get(0);
                List<CalendarViewEvent> viewEvents = list.getEvents();
                for (CalendarViewEvent event : viewEvents) {
                    if (event.getOncourseSiteId() != null) {
                        calendarCourseIds.add(event.getOncourseSiteId().toLowerCase());
                    }
                }
            }
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
        }

        url = configParamService.findValueByName("Sakai.Url.Base") + "site.json";
        is = oncourseOAuthService.oAuthGetRequest(user, url, "text/html");
        String siteJson = IOUtils.toString(is.getBody(), "UTF-8");

        Home home = new Home();
        List<Term> courses = home.getCourses();
        List<Site> projects = home.getProjects();
        List<Site> other = home.getOther();
        List<Site> today = home.getTodaysCourses();
        Map<String, Term> courseMap = new HashMap<String, Term>();
        Map<String, Site> courseSiteMap = new HashMap<String, Site>();
        List<String> courseSiteIdList = new ArrayList<String>();
        JSONObject jsonObj = (JSONObject) JSONSerializer.toJSON(siteJson);
        JSONArray itemArray = jsonObj.getJSONArray("site_collection");
        for (Iterator<JSONObject> iter = itemArray.iterator(); iter.hasNext();) {
            JSONObject object = iter.next();

            String id = object.getString("id");
            if (!visibleSiteIds.contains(id)) {
                continue;
            }

            Site item = new Site();
            item.setId(id);
            item.setTitle(object.getString("title"));
            item.setDescription(object.getString("shortDescription").replace("&nbsp;", " "));

            String type = object.getString("type");
            if ("course".equals(type)) {
                Object jsonProps = object.get("props");
                String term = null;
                if (jsonProps instanceof JSONObject) {
                    JSONObject props = (JSONObject) jsonProps;
                    try {
                        term = props.getString("term");
                        term = term.toLowerCase();
                        String[] split = term.split(" ");
                        term = "";
                        for (String s : split) {
                            s = s.substring(0, 1).toUpperCase() + s.substring(1);
                            term = term + s + " ";
                        }
                        term.trim();
                    } catch (Exception e) {
                    }
                }
                item.setTerm(term);

                Term termObj = courseMap.get(term);
                if (termObj == null) {
                    termObj = new Term();
                    termObj.setTerm(term);
                    courseMap.put(term, termObj);
                }
                termObj.getCourses().add(item);

                courseSiteMap.put(item.getId(), item);
                courseSiteIdList.add(item.getId());

                if (calendarCourseIds.contains(item.getId().toLowerCase())) {
                    today.add(item);
                }
            } else if ("project".equals(type)) {
                projects.add(item);
            } else {
                other.add(item);
            }
        }

        //            try {
        //            List<ViewDetailedEvent> listViewEvents = calendarEventOAuthService.retrieveCourseEvents(user, courseSiteIdList);
        //            for (ViewDetailedEvent event : listViewEvents) {
        //               Site site = courseSiteMap.get(event.getOncourseSiteId());
        //               if (event.getRecurrenceMessage() != null && !event.getRecurrenceMessage().isEmpty()) {
        //                  site.setMeetingTime(event.getRecurrenceMessage());
        //               } else {
        //                  site.setMeetingTime(event.getDisplayDate());
        //               }
        //               site.setLocation(event.getLocation());
        //               site.setBuildingCode(event.getLocationId());
        //            }
        //         } catch (Exception e) {
        //            LOG.error(e.getMessage(), e);
        //         }

        for (Map.Entry<String, Term> entry : courseMap.entrySet()) {
            courses.add(entry.getValue());
        }
        Collections.sort(courses);
        Collections.reverse(courses);
        return home;
    } catch (Exception e) {
        LOG.error(e.getMessage(), e);
        return new Home();
    }
}