Example usage for java.util List sort

List of usage examples for java.util List sort

Introduction

In this page you can find the example usage for java.util List sort.

Prototype

@SuppressWarnings({ "unchecked", "rawtypes" })
default void sort(Comparator<? super E> c) 

Source Link

Document

Sorts this list according to the order induced by the specified Comparator .

Usage

From source file:org.apache.hyracks.control.common.config.ConfigManager.java

@SuppressWarnings({ "squid:S106", "squid:S1147" }) // use of System.err, System.exit()
private List<String> processCommandLine(Collection<Section> sections, OptionHandlerFilter usageFilter,
        BiConsumer<IOption, Object> setAction) throws CmdLineException {
    final Args4jBean bean = new Args4jBean();
    CmdLineParser cmdLineParser = new CmdLineParser(bean);
    final List<String> appArgs = new ArrayList<>();
    List<IOption> commandLineOptions = new ArrayList<>();
    for (Map.Entry<Section, Map<String, IOption>> sectionMapEntry : sectionMap.entrySet()) {
        if (!sections.contains(sectionMapEntry.getKey())) {
            continue;
        }/*www  .  j av a  2  s.c  om*/
        for (IOption option : sectionMapEntry.getValue().values()) {
            if (option.section() != Section.VIRTUAL) {
                commandLineOptions.add(option);
            }
        }
    }
    commandLineOptions.sort(Comparator.comparing(IOption::cmdline));

    commandLineOptions.forEach(option -> cmdLineParser.addOption(new Args4jSetter(option, setAction, false),
            new Args4jOption(option, this, option.type().targetType())));

    if (!argListeners.isEmpty()) {
        cmdLineParser.addArgument(new Args4jSetter(o -> appArgs.add(String.valueOf(o)), true, String.class),
                new Args4jArgument());
    }
    LOGGER.fine("parsing cmdline: " + Arrays.toString(args));
    if (args == null || args.length == 0) {
        LOGGER.info("no command line args supplied");
        return appArgs;
    }
    try {
        cmdLineParser.parseArgument(args);
    } catch (CmdLineException e) {
        if (!bean.help) {
            ConfigUtils.printUsage(e, usageFilter, System.err);
            throw e;
        } else {
            LOGGER.log(Level.FINE, "Ignoring parse exception due to -help", e);
        }
    }
    if (bean.help) {
        ConfigUtils.printUsage(cmdLineParser, usageFilter, System.err);
        System.exit(0);
    } else if (bean.version) {
        System.err.println(versionString);
        System.exit(0);
    }
    return appArgs;
}

From source file:org.opencb.opencga.app.cli.analysis.VariantCommandExecutor.java

private void query() throws Exception {

    AnalysisCliOptionsParser.QueryVariantCommandOptions cliOptions = variantCommandOptions.queryVariantCommandOptions;

    Map<Long, String> studyIds = getStudyIds(sessionId);
    Query query = VariantQueryCommandUtils.parseQuery(cliOptions, studyIds);
    QueryOptions queryOptions = VariantQueryCommandUtils.parseQueryOptions(cliOptions);

    VariantFetcher variantFetcher = new VariantFetcher(catalogManager, storageManagerFactory);

    if (cliOptions.count) {
        QueryResult<Long> result = variantFetcher.count(query, sessionId);
        System.out.println("Num. results\t" + result.getResult().get(0));
    } else if (StringUtils.isNotEmpty(cliOptions.groupBy)) {
        ObjectMapper objectMapper = new ObjectMapper();
        QueryResult groupBy = variantFetcher.groupBy(query, queryOptions, cliOptions.groupBy, sessionId);
        System.out//  ww  w  . j a  v  a  2  s .  c o  m
                .println("rank = " + objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(groupBy));
    } else if (StringUtils.isNotEmpty(cliOptions.rank)) {
        ObjectMapper objectMapper = new ObjectMapper();
        QueryResult rank = variantFetcher.rank(query, queryOptions, cliOptions.rank, sessionId);
        System.out.println("rank = " + objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(rank));
    } else {
        final String outputFormat;
        if (StringUtils.isNotEmpty(cliOptions.outputFormat)) {
            outputFormat = cliOptions.outputFormat.toLowerCase();
        } else {
            outputFormat = "vcf";
        }

        try (OutputStream outputStream = VariantQueryCommandUtils.getOutputStream(cliOptions);
                VariantDBIterator iterator = variantFetcher.iterator(query, queryOptions, sessionId)) {

            StudyConfiguration studyConfiguration;
            final DataWriter<Variant> exporter;
            switch (VariantQueryCommandUtils.VariantOutputFormat.safeValueOf(outputFormat)) {
            case VCF:
                //                StudyConfigurationManager studyConfigurationManager = variantDBAdaptor.getStudyConfigurationManager();
                //                Map<Long, List<Sample>> samplesMetadata = variantFetcher.getSamplesMetadata(studyId, query, queryOptions, sessionId);
                //                QueryResult<StudyConfiguration> studyConfigurationResult = studyConfigurationManager.getStudyConfiguration(
                //                        query.getAsStringList(RETURNED_STUDIES.key()).get(0), null);
                studyConfiguration = variantFetcher.getStudyConfiguration(
                        query.getAsIntegerList(RETURNED_STUDIES.key()).get(0), null, sessionId);
                if (studyConfiguration != null) {
                    // Samples to be returned
                    if (query.containsKey(RETURNED_SAMPLES.key())) {
                        queryOptions.put(RETURNED_SAMPLES.key(), query.get(RETURNED_SAMPLES.key()));
                    }

                    //                        options.add("includeAnnotations", queryVariantsCommandOptions.includeAnnotations);
                    if (cliOptions.annotations != null) {
                        queryOptions.add("annotations", cliOptions.annotations);
                    }
                    //                            VariantVcfExporter.htsExport(iterator, studyConfiguration, outputStream, queryOptions);
                    long studyId = variantFetcher.getMainStudyId(query);
                    VariantSourceDBAdaptor sourceDBAdaptor = variantFetcher.getSourceDBAdaptor((int) studyId,
                            sessionId);
                    exporter = new VariantVcfExporter(studyConfiguration, sourceDBAdaptor, outputStream,
                            queryOptions);
                } else {
                    throw new IllegalArgumentException(
                            "No study found named " + query.getAsStringList(RETURNED_STUDIES.key()).get(0));
                }
                break;
            case JSON:
                // we know that it is JSON, otherwise we have not reached this point
                exporter = batch -> {
                    batch.forEach(variant -> {
                        try {
                            outputStream.write(variant.toJson().getBytes());
                            outputStream.write('\n');
                        } catch (IOException e) {
                            throw new UncheckedIOException(e);
                        }
                    });
                    return true;
                };

                break;
            case AVRO:
                String codecName = "";
                if (VariantQueryCommandUtils.VariantOutputFormat.isGzip(outputFormat)) {
                    codecName = "gzip";
                }
                if (outputFormat.endsWith("snappy")) {
                    codecName = "snappy";
                }
                exporter = new VariantAvroWriter(VariantAvro.getClassSchema(), codecName, outputStream);

                break;
            case STATS:
                studyConfiguration = variantFetcher.getStudyConfiguration(
                        query.getAsIntegerList(RETURNED_STUDIES.key()).get(0), null, sessionId);
                List<String> cohorts = new ArrayList<>(studyConfiguration.getCohortIds().keySet());
                cohorts.sort(String::compareTo);

                exporter = new VariantStatsTsvExporter(outputStream, studyConfiguration.getStudyName(),
                        cohorts);

                break;
            case CELLBASE:
                exporter = new VariantStatsPopulationFrequencyExporter(outputStream);
                break;
            default:
                throw new ParameterException("Unknown output format " + outputFormat);
            }

            ParallelTaskRunner.Task<Variant, Variant> progressTask;
            ExecutorService executor;
            if (VariantQueryCommandUtils.isStandardOutput(cliOptions)) {
                progressTask = batch -> batch;
                executor = null;
            } else {
                executor = Executors.newSingleThreadExecutor();
                Future<Long> future = executor.submit(() -> {
                    Long count = variantFetcher.count(query, sessionId).first();
                    count = Math.min(queryOptions.getLong(QueryOptions.LIMIT, Long.MAX_VALUE),
                            count - queryOptions.getLong(QueryOptions.SKIP, 0));
                    return count;
                });
                executor.shutdown();
                ProgressLogger progressLogger = new ProgressLogger("Export variants", future, 200);
                progressTask = batch -> {
                    progressLogger.increment(batch.size());
                    return batch;
                };
            }
            ParallelTaskRunner.Config config = ParallelTaskRunner.Config.builder().setNumTasks(1)
                    .setBatchSize(10).setAbortOnFail(true).build();
            ParallelTaskRunner<Variant, Variant> ptr = new ParallelTaskRunner<>(batchSize -> {
                List<Variant> variants = new ArrayList<>(batchSize);
                while (iterator.hasNext() && variants.size() < batchSize) {
                    variants.add(iterator.next());
                }
                return variants;
            }, progressTask, exporter, config);

            ptr.run();
            if (executor != null) {
                executor.shutdownNow();
            }
            logger.info(
                    "Time fetching data: " + iterator.getTimeFetching(TimeUnit.MILLISECONDS) / 1000.0 + "s");
            logger.info("Time converting data: " + iterator.getTimeConverting(TimeUnit.MILLISECONDS) / 1000.0
                    + "s");

        }
    }
}

From source file:com.qwazr.search.index.IndexInstance.java

private List<BackupStatus> backups() {
    List<BackupStatus> list = new ArrayList<BackupStatus>();
    if (!fileSet.backupDirectory.exists())
        return list;
    File[] dirs = fileSet.backupDirectory.listFiles((FileFilter) DirectoryFileFilter.INSTANCE);
    if (dirs == null)
        return list;
    for (File dir : dirs) {
        BackupStatus status = BackupStatus.newBackupStatus(dir);
        if (status != null)
            list.add(status);/*from  w ww  .  ja  v a2  s  .c o  m*/
    }
    list.sort(new Comparator<BackupStatus>() {
        @Override
        public int compare(BackupStatus o1, BackupStatus o2) {
            return o2.generation.compareTo(o1.generation);
        }
    });
    return list;
}

From source file:jenkins.security.apitoken.ApiTokenStatsTest.java

@Test
@SuppressWarnings("unchecked")
public void testInternalComparator() throws Exception {
    List<ApiTokenStats.SingleTokenStats> tokenStatsList = Arrays.asList(
            createSingleTokenStatsByReflection("A", null, 0),
            createSingleTokenStatsByReflection("B", "2018-05-01 09:10:59.234", 2),
            createSingleTokenStatsByReflection("C", "2018-05-01 09:10:59.234", 3),
            createSingleTokenStatsByReflection("D", "2018-05-01 09:10:59.235", 1));

    Field field = ApiTokenStats.SingleTokenStats.class.getDeclaredField("COMP_BY_LAST_USE_THEN_COUNTER");
    field.setAccessible(true);/*from  w w  w.j  ava 2 s . co  m*/
    Comparator<ApiTokenStats.SingleTokenStats> comparator = (Comparator<ApiTokenStats.SingleTokenStats>) field
            .get(null);

    // to be not impacted by the declaration order
    Collections.shuffle(tokenStatsList, new Random(42));
    tokenStatsList.sort(comparator);

    List<String> idList = tokenStatsList.stream().map(ApiTokenStats.SingleTokenStats::getTokenUuid)
            .collect(Collectors.toList());

    assertThat(idList, contains("A", "B", "C", "D"));
}

From source file:org.keycloak.models.jpa.JpaRealmProvider.java

@Override
public List<GroupModel> searchForGroupByName(RealmModel realm, String search, Integer first, Integer max) {
    TypedQuery<String> query = em.createNamedQuery("getGroupIdsByNameContaining", String.class)
            .setParameter("realm", realm.getId()).setParameter("search", search);
    if (Objects.nonNull(first) && Objects.nonNull(max)) {
        query = query.setFirstResult(first).setMaxResults(max);
    }/*from  w w  w  . j av a2  s  .  c  om*/
    List<String> groups = query.getResultList();
    if (Objects.isNull(groups))
        return Collections.EMPTY_LIST;
    List<GroupModel> list = new ArrayList<>();
    for (String id : groups) {
        GroupModel groupById = session.realms().getGroupById(id, realm);
        while (Objects.nonNull(groupById.getParentId())) {
            groupById = session.realms().getGroupById(groupById.getParentId(), realm);
        }
        if (!list.contains(groupById)) {
            list.add(groupById);
        }
    }
    list.sort(Comparator.comparing(GroupModel::getName));

    return Collections.unmodifiableList(list);
}

From source file:com.adobe.acs.commons.mcp.impl.processes.asset.UrlAssetImport.java

private Optional<FileOrRendition> findOriginalRendition(Collection<FileOrRendition> allFiles,
        FileOrRendition rendition) {//w w w.  j a va2s .c  o  m
    // Build list of files in the target folder
    List<FileOrRendition> filesInFolder = allFiles.stream()
            .filter(f -> f.getParent().getNodePath().equals(rendition.getParent().getNodePath()))
            .collect(Collectors.toList());

    if (filesInFolder.isEmpty()) {
        LOG.error("Unable to find any other files in directory " + rendition.getParent().getNodePath());
        return Optional.empty();
    } else {
        // Organize files by closest match (better match = smaller levensthein distance)
        String fileName = rendition.getOriginalAssetName() == null || rendition.getOriginalAssetName().isEmpty()
                ? rendition.getName().toLowerCase()
                : rendition.getOriginalAssetName().toLowerCase();
        filesInFolder.sort((a, b) -> compareName(a, b, fileName));

        // Return best match
        return Optional.of(filesInFolder.get(0));
    }
}

From source file:org.sakaiproject.poll.logic.impl.PollOrderOptionBackFillJob.java

/**
 * This is the method that is fired when the job is 'triggered'.
 *
 * @param jobExecutionContext - the context of the job execution
 * @throws JobExecutionException/* w  w w  . j  a  v a 2s.c  o  m*/
 */
@Override
public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
    log.info("Attempting to back-fill all existing Poll option orders...");
    int modifiedCount = 0;

    // Iterate over sites in the system, ordered by creation date...
    List<Site> sites = siteService.getSites(SelectionType.ANY, null, null, null, SortType.CREATED_ON_DESC,
            null);
    if (!CollectionUtils.isEmpty(sites)) {
        for (Site site : sites) {
            String siteID = site.getId();
            List<Poll> pollsForSite = pollService.findAllPolls(siteID);
            if (!CollectionUtils.isEmpty(pollsForSite)) {
                // Iterate over the polls for the site...
                for (Poll poll : pollsForSite) {
                    try {
                        // Iterate over Options in the poll...
                        securityService.pushAdvisor(YES_MAN);
                        List<Option> pollOptions = pollService.getOptionsForPoll(poll);
                        if (!CollectionUtils.isEmpty(pollOptions)) {
                            // Check if any options have a null order
                            boolean hasNullOptionOrder = false;
                            for (Option option : pollOptions) {
                                if (option.getOptionOrder() == null) {
                                    hasNullOptionOrder = true;
                                    break;
                                }
                            }

                            // If any of the option's order is null, we need to back-fill them
                            if (hasNullOptionOrder) {
                                log.info("Poll ID {} has options with null order, processing...", poll.getId());

                                // Order the list by ID
                                pollOptions.sort(Comparator.comparingLong(Option::getOptionId));

                                // Iterate over the list
                                for (int i = 0; i < pollOptions.size(); i++) {
                                    // Add order based on ID
                                    Option option = pollOptions.get(i);
                                    option.setOptionOrder(i);
                                    pollService.saveOption(option);
                                    modifiedCount++;
                                    log.info("Option {} ---> new order == {}", option.getId(), i);
                                }
                            }
                        }
                    } catch (Exception ex) {
                        log.error("Unexcepted exception", ex);
                    } finally {
                        securityService.popAdvisor(YES_MAN);
                    }
                }
            }
        }
    }

    log.info("Processing finished, modified {} poll options", modifiedCount);
}

From source file:org.silverpeas.core.contribution.attachment.SimpleDocumentService.java

@Override
public List<SimpleDocument> listDocumentsLockedByUser(String usedId, String language) {
    try (JcrSession session = openSystemSession()) {
        final List<SimpleDocument> documents = repository.listDocumentsLockedByUser(session, usedId, language);
        documents.sort((o1, o2) -> o2.getUpdated().compareTo(o1.getUpdated()));
        return documents;
    } catch (RepositoryException ex) {
        throw new AttachmentException(ex);
    }/*from  www .j ava2 s  .  co  m*/
}

From source file:org.cgiar.ccafs.marlo.action.annualReport.FinancialSummaryAction.java

@Override
public void prepare() throws Exception {
    // Get current CRP
    loggedCrp = (GlobalUnit) this.getSession().get(APConstants.SESSION_CRP);
    loggedCrp = crpManager.getGlobalUnitById(loggedCrp.getId());
    Phase phase = this.getActualPhase();

    // If there is a history version being loaded
    if (this.getRequest().getParameter(APConstants.TRANSACTION_ID) != null) {
        transaction = StringUtils.trim(this.getRequest().getParameter(APConstants.TRANSACTION_ID));
        ReportSynthesis history = (ReportSynthesis) auditLogManager.getHistory(transaction);
        if (history != null) {
            reportSynthesis = history;//from w  w w .j  a  v  a 2s  . c om
            synthesisID = reportSynthesis.getId();
        } else {
            this.transaction = null;
            this.setTransaction("-1");
        }
    } else {
        // Get Liaison institution ID Parameter
        try {
            liaisonInstitutionID = Long.parseLong(StringUtils
                    .trim(this.getRequest().getParameter(APConstants.LIAISON_INSTITUTION_REQUEST_ID)));
        } catch (NumberFormatException e) {
            User user = userManager.getUser(this.getCurrentUser().getId());
            if (user.getLiasonsUsers() != null || !user.getLiasonsUsers().isEmpty()) {
                List<LiaisonUser> liaisonUsers = new ArrayList<>(user.getLiasonsUsers().stream()
                        .filter(lu -> lu.isActive() && lu.getLiaisonInstitution().isActive()
                                && lu.getLiaisonInstitution().getCrp().getId() == loggedCrp.getId()
                                && lu.getLiaisonInstitution().getInstitution() == null)
                        .collect(Collectors.toList()));
                if (!liaisonUsers.isEmpty()) {
                    boolean isLeader = false;
                    for (LiaisonUser liaisonUser : liaisonUsers) {
                        LiaisonInstitution institution = liaisonUser.getLiaisonInstitution();
                        if (institution.isActive()) {
                            if (institution.getCrpProgram() != null) {
                                if (institution.getCrpProgram()
                                        .getProgramType() == ProgramType.FLAGSHIP_PROGRAM_TYPE.getValue()) {
                                    liaisonInstitutionID = institution.getId();
                                    isLeader = true;
                                    break;
                                }
                            } else {
                                if (institution.getAcronym().equals("PMU")) {
                                    liaisonInstitutionID = institution.getId();
                                    isLeader = true;
                                    break;
                                }
                            }
                        }
                    }
                    if (!isLeader) {
                        liaisonInstitutionID = this.firstFlagship();
                    }
                } else {
                    liaisonInstitutionID = this.firstFlagship();
                }
            } else {
                liaisonInstitutionID = this.firstFlagship();
            }
        }

        try {
            synthesisID = Long.parseLong(
                    StringUtils.trim(this.getRequest().getParameter(APConstants.REPORT_SYNTHESIS_ID)));
            reportSynthesis = reportSynthesisManager.getReportSynthesisById(synthesisID);

            if (!reportSynthesis.getPhase().equals(phase)) {
                reportSynthesis = reportSynthesisManager.findSynthesis(phase.getId(), liaisonInstitutionID);
                if (reportSynthesis == null) {
                    reportSynthesis = this.createReportSynthesis(phase.getId(), liaisonInstitutionID);
                }
                synthesisID = reportSynthesis.getId();
            }
        } catch (Exception e) {
            reportSynthesis = reportSynthesisManager.findSynthesis(phase.getId(), liaisonInstitutionID);
            if (reportSynthesis == null) {
                reportSynthesis = this.createReportSynthesis(phase.getId(), liaisonInstitutionID);
            }
            synthesisID = reportSynthesis.getId();
        }
    }

    if (reportSynthesis != null) {

        ReportSynthesis reportSynthesisDB = reportSynthesisManager
                .getReportSynthesisById(reportSynthesis.getId());
        synthesisID = reportSynthesisDB.getId();
        liaisonInstitutionID = reportSynthesisDB.getLiaisonInstitution().getId();
        liaisonInstitution = liaisonInstitutionManager.getLiaisonInstitutionById(liaisonInstitutionID);

        Path path = this.getAutoSaveFilePath();
        // Verify if there is a Draft file
        if (path.toFile().exists() && this.getCurrentUser().isAutoSave()) {
            BufferedReader reader;
            reader = new BufferedReader(new FileReader(path.toFile()));
            Gson gson = new GsonBuilder().create();
            JsonObject jReader = gson.fromJson(reader, JsonObject.class);
            reader.close();
            AutoSaveReader autoSaveReader = new AutoSaveReader();
            reportSynthesis = (ReportSynthesis) autoSaveReader.readFromJson(jReader);
            synthesisID = reportSynthesis.getId();
            this.setDraft(true);
        } else {

            this.setDraft(false);
            // Check if relation is null -create it
            if (reportSynthesis.getReportSynthesisFinancialSummary() == null) {
                ReportSynthesisFinancialSummary financialSummary = new ReportSynthesisFinancialSummary();
                // create one to one relation
                reportSynthesis.setReportSynthesisFinancialSummary(financialSummary);
                ;
                financialSummary.setReportSynthesis(reportSynthesis);
                // save the changes
                reportSynthesis = reportSynthesisManager.saveReportSynthesis(reportSynthesis);
            }

            reportSynthesis.getReportSynthesisFinancialSummary().setBudgets(new ArrayList<>());
            if (this.isPMU()) {
                // Flagships Financial Budgets
                if (reportSynthesis.getReportSynthesisFinancialSummary()
                        .getReportSynthesisFinancialSummaryBudgets() != null
                        && !reportSynthesis.getReportSynthesisFinancialSummary()
                                .getReportSynthesisFinancialSummaryBudgets().isEmpty()) {
                    reportSynthesis.getReportSynthesisFinancialSummary()
                            .setBudgets(new ArrayList<>(reportSynthesis.getReportSynthesisFinancialSummary()
                                    .getReportSynthesisFinancialSummaryBudgets().stream()
                                    .filter(t -> t.isActive()).collect(Collectors.toList())));
                } else {

                    List<LiaisonInstitution> flagshipList = loggedCrp.getLiaisonInstitutions().stream()
                            .filter(c -> c.getCrpProgram() != null && c.isActive() && c.getCrpProgram()
                                    .getProgramType() == ProgramType.FLAGSHIP_PROGRAM_TYPE.getValue())
                            .collect(Collectors.toList());
                    flagshipList.sort(Comparator.comparing(LiaisonInstitution::getAcronym));
                    reportSynthesis.getReportSynthesisFinancialSummary().setBudgets(new ArrayList<>());
                    for (LiaisonInstitution liInstitution : flagshipList) {
                        ReportSynthesisFinancialSummaryBudget financialSummaryBudget = new ReportSynthesisFinancialSummaryBudget();
                        financialSummaryBudget.setLiaisonInstitution(liInstitution);
                        reportSynthesis.getReportSynthesisFinancialSummary().getBudgets()
                                .add(financialSummaryBudget);
                    }

                    List<PowbExpenditureAreas> expAreas = new ArrayList<>(powbExpenditureAreasManager.findAll()
                            .stream().filter(x -> x.isActive() && !x.getIsExpenditure())
                            .collect(Collectors.toList()));
                    for (PowbExpenditureAreas powbExpenditureAreas : expAreas) {
                        ReportSynthesisFinancialSummaryBudget financialSummaryBudget = new ReportSynthesisFinancialSummaryBudget();
                        financialSummaryBudget.setExpenditureArea(powbExpenditureAreas);
                        reportSynthesis.getReportSynthesisFinancialSummary().getBudgets()
                                .add(financialSummaryBudget);
                    }

                }
            }
        }
    }

    // Get the list of liaison institutions Flagships and PMU.
    liaisonInstitutions = loggedCrp.getLiaisonInstitutions().stream()
            .filter(c -> c.getCrpProgram() != null && c.isActive()
                    && c.getCrpProgram().getProgramType() == ProgramType.FLAGSHIP_PROGRAM_TYPE.getValue())
            .collect(Collectors.toList());
    liaisonInstitutions.sort(Comparator.comparing(LiaisonInstitution::getAcronym));

    // ADD PMU as liasion Institution too
    liaisonInstitutions.addAll(loggedCrp.getLiaisonInstitutions().stream()
            .filter(c -> c.getCrpProgram() == null && c.isActive() && c.getAcronym().equals("PMU"))
            .collect(Collectors.toList()));

    // Informative table to Flagships
    if (this.isFlagship()) {
        LiaisonInstitution pmuInstitution = loggedCrp.getLiaisonInstitutions().stream()
                .filter(c -> c.getCrpProgram() == null && c.getAcronym().equals("PMU"))
                .collect(Collectors.toList()).get(0);
        ReportSynthesis reportSynthesisDB = reportSynthesisManager.findSynthesis(phase.getId(),
                pmuInstitution.getId());
        if (reportSynthesisDB != null) {
            if (reportSynthesisDB.getReportSynthesisFinancialSummary() != null) {
                if (reportSynthesisDB.getReportSynthesisFinancialSummary()
                        .getReportSynthesisFinancialSummaryBudgets() != null
                        && !reportSynthesisDB.getReportSynthesisFinancialSummary()
                                .getReportSynthesisFinancialSummaryBudgets().isEmpty()) {
                    reportSynthesis.getReportSynthesisFinancialSummary()
                            .setBudgets(new ArrayList<>(reportSynthesisDB.getReportSynthesisFinancialSummary()
                                    .getReportSynthesisFinancialSummaryBudgets().stream()
                                    .filter(t -> t.isActive()).collect(Collectors.toList())));
                }
            }
        }
    }

    // Base Permission
    String params[] = { loggedCrp.getAcronym(), reportSynthesis.getId() + "" };
    this.setBasePermission(this.getText(Permission.REPORT_SYNTHESIS_CRP_PROGRESS_BASE_PERMISSION, params));

    if (this.isHttpPost()) {
        if (reportSynthesis.getReportSynthesisFinancialSummary().getBudgets() != null) {
            reportSynthesis.getReportSynthesisFinancialSummary().getBudgets().clear();
        }
    }
}