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:com.edgenius.wiki.security.strategy.PatternStrategy.java

/**
 * Find runtime method pattern, which has inherent relationship.
 *///ww  w  .  j av a  2s  .  c  om
public WikiOPERATIONS findURLRuntimePattern(String source) {

    WikiOPERATIONS wo = null;
    List<String> patterns = new ArrayList<String>(urlPatternMap.keySet());
    Collections.sort(patterns);
    Collections.reverse(patterns);
    for (String pattern : patterns) {
        if (pathMatcher.match(pattern, source)) {
            wo = urlPatternMap.get(pattern);
            //for system default URL pattern, it return null, such as login.do
            if (wo != null) {
                //fill value: the value could be spaceUname or PageUuid, depends on the resource type 
                Map<RESOURCE_TYPES, String> values = null;
                if (urlValueProviderList != null) {
                    for (URLValueProvider provider : urlValueProviderList) {
                        if (provider.isSupport(wo)) {
                            values = provider.getParameters(source, pattern);
                        }

                    }
                }
                if (values == null) {
                    if (wo.type == RESOURCE_TYPES.INSTANCE) {
                        //it maybe Instance scope validation
                        values = new HashMap<RESOURCE_TYPES, String>();
                    } else {
                        //return null:
                        //don't do validation anymore, no value(spaceUname or pageUuid) for space or page level security check 
                        return null;
                    }
                }
                //always put instance to value map
                values.put(RESOURCE_TYPES.INSTANCE, WikiConstants.CONST_INSTANCE_RESOURCE_NAME);
                wo.values = values;
            }
            break;
        }
    }
    return wo;

}

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

/**
 * Calculates the "hubs-and-authorities" importance measures for each node
 * in a graph. These measures are defined recursively as follows: 1. The
 * *hubness* of a node is the degree to which a node links to other
 * important authorities 2. The *authoritativeness* of a node is the degree
 * to which a node is pointed to by important hubs
 *
 * @return A list of nodes with their HITS rankings in descending order.
 *///w ww  .  ja  va2 s  . c o m
@Override
public List<String> getHITS() {

    logger.info("Getting HITS...");
    HITS<Entity, EntityGraphEdge> ranker = new HITS<Entity, EntityGraphEdge>(directedGraph);
    logger.info("Ranker was created.");
    logger.info("Evaluating...");
    ranker.evaluate();

    logger.info("Got HITS.");
    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 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.becool.base.spring.tx.ChainedTransactionManager.java

private <T> Iterable<T> reverse(Collection<T> collection) {

    List<T> list = new ArrayList<T>(collection);
    Collections.reverse(list);
    return list;//from w  ww  .ja v  a 2 s.  c o m
}

From source file:fr.mcc.ginco.extjs.view.utils.ThesaurusViewConverter.java

/**
 * Main method for conversion from object to view.
 *
 * @param source object to get data from.
 * @return view object./*w  w  w .ja  v  a2  s . c o m*/
 */
public ThesaurusView convert(Thesaurus source) {
    ThesaurusView view = new ThesaurusView();
    if (source != null) {
        view.setId(source.getIdentifier());
        view.setContributor(source.getContributor());
        view.setCoverage(source.getCoverage());

        if (source.getDate() != null) {
            view.setDate(DateUtil.toString(source.getDate()));
        }
        view.setDescription(source.getDescription());
        view.setPublisher(source.getPublisher());
        view.setRelation(source.getRelation());
        view.setRights(source.getRights());
        view.setSource(source.getSource());
        view.setSubject(source.getSubject());
        view.setTitle(source.getTitle());
        view.setCreated(DateUtil.toString(source.getCreated()));

        if (source.getCreator() != null) {
            view.setCreatorName(source.getCreator().getName());
            view.setCreatorHomepage(source.getCreator().getHomepage());
            view.setCreatorEmail(source.getCreator().getEmail());
        }

        if (source.isDefaultTopConcept() != null) {
            view.setDefaultTopConcept(source.isDefaultTopConcept());
        } else {
            view.setDefaultTopConcept(false);
        }

        view.setArchived(source.isArchived());

        List<Integer> formatList = new ArrayList<Integer>();
        for (ThesaurusFormat format : source.getFormat()) {
            formatList.add(format.getIdentifier());
        }
        view.setFormats(formatList);

        if (source.getType() != null) {
            view.setType(source.getType().getIdentifier());
        }

        List<Language> langList = new ArrayList<Language>();
        for (Language lang : source.getLang()) {
            langList.add(lang);
        }
        Collections.sort(langList, new LanguageComparator(defaultLanguage));
        Collections.reverse(langList);
        List<String> langLabels = new ArrayList<String>();
        for (Language lang : langList) {
            langLabels.add(lang.getId());
        }
        view.setLanguages(langLabels);

        boolean isArchived;
        if (source.isArchived() != null) {
            isArchived = source.isArchived();
        } else {
            isArchived = false;
        }

        if (thesaurusVersionHistoryService.hasPublishedVersion(source) && !isArchived) {
            view.setCanBeDeleted(false);
        } else {
            view.setCanBeDeleted(true);
        }
        view.setPolyHierarchical(source.isPolyHierarchical());
    }
    return view;
}

From source file:net.sf.jdmf.algorithms.classification.util.AttributeValuePartitioner.java

protected Comparable determineLastPartitionAttributeValue(List<AttributeValueIncidence> majorityClassExamples,
        AttributeValueIncidenceComparator incidenceComparator) {
    log.debug("majorityClassExamples.size()=" + majorityClassExamples.size());

    Collections.sort(majorityClassExamples, incidenceComparator);
    Collections.reverse(majorityClassExamples);

    int valuesWithHighestIncidenceCount = 1;

    for (int i = 0; i < majorityClassExamples.size() - 1; ++i) {
        if (incidenceComparator.compare(majorityClassExamples.get(i), majorityClassExamples.get(i + 1)) == 0) {
            ++valuesWithHighestIncidenceCount;
        } else {/*from www . j a  v  a2s .  com*/
            break;
        }
    }

    log.debug("valuesWithHighestIncidenceCount=" + valuesWithHighestIncidenceCount);

    Random random = new Random();
    AttributeValueIncidence attributeValueIncidence = majorityClassExamples
            .get(random.nextInt(valuesWithHighestIncidenceCount));

    return attributeValueIncidence.getAttributeValue();
}

From source file:de.blizzy.documentr.search.PageFinder.java

private SearchTextSuggestion getSearchTextSuggestion(String searchText, Authentication authentication,
        IndexSearcher searcher) throws IOException, ParseException, TimeoutException {

    List<WordPosition> words = Lists.newArrayList();

    TokenStream tokenStream = null;/*from   w  ww  . ja v  a 2  s . c o m*/
    try {
        tokenStream = analyzer.tokenStream(PageIndex.ALL_TEXT_SUGGESTIONS, new StringReader(searchText));
        tokenStream.addAttribute(CharTermAttribute.class);
        tokenStream.addAttribute(OffsetAttribute.class);
        tokenStream.reset();
        while (tokenStream.incrementToken()) {
            CharTermAttribute charTerm = tokenStream.getAttribute(CharTermAttribute.class);
            String text = charTerm.toString();
            if (StringUtils.isNotBlank(text)) {
                OffsetAttribute offset = tokenStream.getAttribute(OffsetAttribute.class);
                WordPosition word = new WordPosition(text, offset.startOffset(), offset.endOffset());
                words.add(word);
            }
        }
        tokenStream.end();
    } finally {
        Util.closeQuietly(tokenStream);
    }

    Collections.reverse(words);

    StringBuilder suggestedSearchText = new StringBuilder(searchText);
    StringBuilder suggestedSearchTextHtml = new StringBuilder(searchText);
    boolean foundSuggestions = false;
    String now = String.valueOf(System.currentTimeMillis());
    String startMarker = "__SUGGESTION-" + now + "__"; //$NON-NLS-1$ //$NON-NLS-2$
    String endMarker = "__/SUGGESTION-" + now + "__"; //$NON-NLS-1$ //$NON-NLS-2$
    DirectSpellChecker spellChecker = new DirectSpellChecker();
    IndexReader reader = searcher.getIndexReader();
    for (WordPosition word : words) {
        Term term = new Term(PageIndex.ALL_TEXT_SUGGESTIONS, word.getWord());
        SuggestWord[] suggestions = spellChecker.suggestSimilar(term, 1, reader,
                SuggestMode.SUGGEST_MORE_POPULAR);
        if (suggestions.length > 0) {
            String suggestedWord = suggestions[0].string;
            int start = word.getStart();
            int end = word.getEnd();
            suggestedSearchText.replace(start, end, suggestedWord);
            suggestedSearchTextHtml.replace(start, end,
                    startMarker + StringEscapeUtils.escapeHtml4(suggestedWord) + endMarker);

            foundSuggestions = true;
        }
    }

    if (foundSuggestions) {
        String suggestion = suggestedSearchText.toString();
        SearchResult suggestionResult = findPages(suggestion, 1, authentication, searcher);
        int suggestionTotalHits = suggestionResult.getTotalHits();
        if (suggestionTotalHits > 0) {
            String html = StringEscapeUtils.escapeHtml4(suggestedSearchTextHtml.toString())
                    .replaceAll(startMarker + "(.*?)" + endMarker, "<strong><em>$1</em></strong>"); //$NON-NLS-1$ //$NON-NLS-2$
            return new SearchTextSuggestion(suggestedSearchText.toString(), html, suggestionTotalHits);
        }
    }

    return null;
}

From source file:org.squale.squaleweb.applicationlayer.action.results.audit.AuditAction.java

/**
 * Permet la slection d'audits  afficher.
 * /*w  w w  .j  a  va2  s  .  co  m*/
 * @param pMapping le mapping.
 * @param pForm le formulaire  lire.
 * @param pRequest la requte HTTP.
 * @param pResponse la rponse de la servlet.
 * @return l'action  raliser.
 */
public ActionForward select(ActionMapping pMapping, ActionForm pForm, HttpServletRequest pRequest,
        HttpServletResponse pResponse) {
    ActionErrors errors = new ActionErrors();
    ActionForward forward = new ActionForward();
    try {
        List auditsSelected = getAuditsSelected(pForm, pRequest);
        // Vrification de la slection
        if (auditsSelected.size() < 1 || auditsSelected.size() > 2) {
            ActionError error = new ActionError("error.invalid_audits_selection");
            errors.add("invalid.selection", error);
        } else {
            Long applicationId = new Long(((AuditForm) auditsSelected.get(0)).getApplicationId());
            pRequest.setAttribute("currentAuditId", "" + ((AuditForm) auditsSelected.get(0)).getId());
            if (auditsSelected.size() == 1) {
                // S'il n'y en a qu'un de slectionn, on choisit aussi le prcdent de la liste
                // s'il existe
                AuditForm audit = getPreviousAudit((AuditForm) auditsSelected.get(0));
                if (null != audit) {
                    auditsSelected.add(audit);
                }
            }
            // On trie les audits dans l'ordre inverse chronologique
            AuditComparator ac = new AuditComparator();
            Collections.sort(auditsSelected, ac);
            Collections.reverse(auditsSelected);

            // On remplit le formulaire qui sera mis en session
            AuditListForm listForm = new AuditListForm();
            listForm.setAudits(auditsSelected);
            // on a russi  rcuprer l'audit prcdent et il n'est pas nul
            if (auditsSelected.size() == 2) {
                pRequest.setAttribute("previousAuditId", "" + ((AuditForm) auditsSelected.get(1)).getId());
            }

            pRequest.removeAttribute("id");
            pRequest.setAttribute("applicationId", applicationId.toString());
            // on dfinit l'audit en cours pour vrification (audit le plus rcent)
            pRequest.setAttribute("audit", auditsSelected.get(0));
            // Forward diffrent selon le type de l'audit
            if (pRequest.getParameter("kind") != null && pRequest.getParameter("kind").equals("failed")) {
                String oldAuditId = pRequest.getParameter("oldAudit");
                String oldPreviousAuditId = pRequest.getParameter("oldPreviousAudit");
                if (null != oldAuditId) {
                    // On le rajoute dans le requte pour pouvoir rcuprer l'action du bouton retour
                    pRequest.setAttribute("oldAuditId", oldAuditId);
                    pRequest.setAttribute("oldPreviousAuditId", oldPreviousAuditId);
                } else {
                    // On met une valeur par dfaut
                    pRequest.setAttribute("oldAuditId", "none");
                    pRequest.setAttribute("oldPreviousAuditId", "none");
                }
                forward = pMapping.findForward("applicationErrors");
            } else {
                forward = pMapping.findForward("application");
            }
            // In all cases, add user access for the application
            addUserAccess(pRequest, applicationId.longValue());
        }
    } catch (Exception e) {
        // Traitement factoris des exceptions
        handleException(e, errors, pRequest);
    }
    if (!errors.isEmpty()) {
        // Enregistrement du message et retour sur la page pour afficher l'erreur
        saveErrors(pRequest, errors);
        forward = pMapping.findForward("failure");
    }
    // pas de tracker ici
    return forward;
}

From source file:com.hellblazer.process.impl.AbstractManagedProcess.java

@Override
public String getStdOutTail(int numLines) throws IOException {
    if (!getStdOutFile().exists()) {
        throw new IllegalThreadStateException("Process has not been started or has already exited");
    }/*from w  ww.  j  a v  a2s.c om*/
    List<String> lines = new ArrayList<>();
    try (ReversedLinesFileReader reader = new ReversedLinesFileReader(getStdOutFile())) {
        int linesRead = 0;
        String line;
        while (((line = reader.readLine()) != null) && (linesRead++ < numLines)) {
            lines.add(line);
        }
    }
    Collections.reverse(lines);
    StringBuilder builder = new StringBuilder();
    for (String line : lines) {
        builder.append(line);
        builder.append('\n');
    }
    return builder.toString();
}

From source file:com.streamsets.pipeline.stage.origin.jdbc.table.ReferentialConstraintOrderingIT.java

@AfterClass
public static void deleteTables() throws SQLException {
    try (Statement statement = connection.createStatement()) {
        List<String> tablesToDelete = new ArrayList<>(TABLE_TO_TEMPLATE_AND_RECORDS_MAP.keySet());
        //Reverse order of tables for deletion.
        Collections.reverse(tablesToDelete);
        for (String tableToDelete : tablesToDelete) {
            statement.addBatch("DROP TABLE TEST." + tableToDelete);
        }/*from  w ww . j a  v  a 2  s  .  co m*/
        statement.executeBatch();
    }
}

From source file:ch.ksfx.util.calc.MovingAverageCalculator.java

public static Double calcExponentialMovingAverageObservation(Integer timeFrameSeconds, Integer timeFramesBack,
        List<Observation> assetPrices, boolean askPrice, boolean acceptCurrentPrice, Observation forcedPriced) {
    //TODO this might be 0
    Observation currentPrice = assetPrices.get(assetPrices.size() - 1);

    List<Observation> aps = AssetPriceSparser.sparseAssetPriceWithoutAveragingObservation(assetPrices,
            timeFrameSeconds);//from   www.  java 2 s  .  c  o  m

    Collections.sort(aps, new ObservationDateComparator());
    Collections.reverse(aps);

    if (forcedPriced != null) {
        if (!forcedPriced.equals(aps.get(0))) {
            return null;
        }
    }

    if (aps.size() < timeFramesBack) {
        logger.info(
                "Cannot calc EMA not enough values, after sparsing we only have: " + aps.size() + " values");

        for (Observation ip : aps) {
            logger.info("Asset Price Pricing Date " + ip.getObservationTime());
        }

        return null;
    }

    List<Observation> relevantPrices = new ArrayList<Observation>();

    if (acceptCurrentPrice) {
        relevantPrices.add(currentPrice);
    } else {
        relevantPrices.add(aps.get(0));
    }

    Integer lastAddedIndex = 0;

    //Shouldn't it be enough to sublist here?
    for (Integer iI = 0; iI < aps.size(); iI++) {
        if (relevantPrices.get(lastAddedIndex).getObservationTime().getTime()
                - aps.get(iI).getObservationTime().getTime() >= timeFrameSeconds) {
            relevantPrices.add(aps.get(iI));

            if (lastAddedIndex > timeFramesBack - 1) {
                break;
            }
        }
    }

    //starting point
    Double average = calculateMovingAverageObservation(relevantPrices, true);

    Double k = 2. / (timeFramesBack + 1.);

    Double ema = 0.0;
    Double emaYesterday = average;

    for (Integer iK = 2; iK <= relevantPrices.size(); iK++) {
        ema = Double.parseDouble(relevantPrices.get(relevantPrices.size() - iK).getScalarValue()) * k
                + emaYesterday * (1. - k);
        emaYesterday = ema;
    }

    logger.info("Calculated EMA " + ema + " - k was " + k);

    return ema;
}