Example usage for java.util Comparator comparing

List of usage examples for java.util Comparator comparing

Introduction

In this page you can find the example usage for java.util Comparator comparing.

Prototype

public static <T, U extends Comparable<? super U>> Comparator<T> comparing(
        Function<? super T, ? extends U> keyExtractor) 

Source Link

Document

Accepts a function that extracts a java.lang.Comparable Comparable sort key from a type T , and returns a Comparator that compares by that sort key.

Usage

From source file:org.cgiar.ccafs.marlo.action.annualReport.CrpProgressAction.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;// w  ww.j  av a  2s .c  o  m
            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);

        // Fill Flagship Expected Studies
        if (this.isFlagship()) {
            this.studiesList(phase.getId(), liaisonInstitution);
        }

        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();

            if (this.isFlagship()) {
                if (reportSynthesis.getReportSynthesisCrpProgress().getPlannedStudiesValue() != null) {
                    String[] studyValues = reportSynthesis.getReportSynthesisCrpProgress()
                            .getPlannedStudiesValue().split(",");
                    reportSynthesis.getReportSynthesisCrpProgress().setExpectedStudies(new ArrayList<>());

                    for (int i = 0; i < studyValues.length; i++) {

                        ProjectExpectedStudy study = projectExpectedStudyManager
                                .getProjectExpectedStudyById(Long.parseLong(studyValues[i]));
                        reportSynthesis.getReportSynthesisCrpProgress().getExpectedStudies().add(study);
                    }
                }
            }

            this.setDraft(true);
        } else {

            this.setDraft(false);
            // Check if relation is null -create it
            if (reportSynthesis.getReportSynthesisCrpProgress() == null) {
                ReportSynthesisCrpProgress crpProgress = new ReportSynthesisCrpProgress();
                // create one to one relation
                reportSynthesis.setReportSynthesisCrpProgress(crpProgress);
                ;
                crpProgress.setReportSynthesis(reportSynthesis);
                // save the changes
                reportSynthesis = reportSynthesisManager.saveReportSynthesis(reportSynthesis);
            }

            if (this.isFlagship()) {
                // Srf Targets List
                if (reportSynthesis.getReportSynthesisCrpProgress()
                        .getReportSynthesisCrpProgressTargets() != null) {
                    reportSynthesis.getReportSynthesisCrpProgress()
                            .setSloTargets(new ArrayList<>(reportSynthesis.getReportSynthesisCrpProgress()
                                    .getReportSynthesisCrpProgressTargets().stream().filter(t -> t.isActive())
                                    .collect(Collectors.toList())));
                }
                // Crp Progress Studies
                reportSynthesis.getReportSynthesisCrpProgress().setExpectedStudies(new ArrayList<>());
                if (reportSynthesis.getReportSynthesisCrpProgress()
                        .getReportSynthesisCrpProgressStudies() != null
                        && !reportSynthesis.getReportSynthesisCrpProgress()
                                .getReportSynthesisCrpProgressStudies().isEmpty()) {
                    for (ReportSynthesisCrpProgressStudy plannedStudy : reportSynthesis
                            .getReportSynthesisCrpProgress().getReportSynthesisCrpProgressStudies().stream()
                            .filter(ro -> ro.isActive()).collect(Collectors.toList())) {
                        reportSynthesis.getReportSynthesisCrpProgress().getExpectedStudies()
                                .add(plannedStudy.getProjectExpectedStudy());
                    }
                }
            }
        }
    }

    if (this.isFlagship()) {
        sloTargets = new ArrayList<>(srfSloIndicatorTargetManager.findAll().stream()
                .filter(sr -> sr.isActive() && sr.getYear() == 2022).collect(Collectors.toList()));
    }

    // 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));

    if (this.isPMU()) {

        // Table A-2 PMU Information
        flagshipPlannedList = reportSynthesisCrpProgressManager.getPlannedList(liaisonInstitutions,
                phase.getId(), loggedCrp, this.liaisonInstitution);
        // Table A-1 Evidence on Progress
        fpSynthesisTable = reportSynthesisCrpProgressTargetManager.flagshipSynthesis(liaisonInstitutions,
                phase.getId());

        // Flagships Synthesis Progress
        flagshipCrpProgress = reportSynthesisCrpProgressManager.getFlagshipCrpProgress(liaisonInstitutions,
                phase.getId());

    }

    // 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()));

    // 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.getReportSynthesisCrpProgress().getSloTargets() != null) {
            reportSynthesis.getReportSynthesisCrpProgress().getSloTargets().clear();
        }

        if (reportSynthesis.getReportSynthesisCrpProgress().getPlannedStudies() != null) {
            reportSynthesis.getReportSynthesisCrpProgress().getPlannedStudies().clear();
        }
    }
}

From source file:org.apache.sysml.hops.codegen.opt.PlanSelectionFuseCostBased.java

private static double rGetPlanCosts(CPlanMemoTable memo, Hop current, HashSet<Pair<Long, Long>> visited,
        HashSet<Long> partition, ArrayList<Long> M, boolean[] plan, HashMap<Long, Double> computeCosts,
        CostVector costsCurrent, TemplateType currentType) {
    //memoization per hop id and cost vector to account for redundant
    //computation without double counting materialized results or compute
    //costs of complex operation DAGs within a single fused operator
    Pair<Long, Long> tag = Pair.of(current.getHopID(), (costsCurrent == null) ? 0 : costsCurrent.ID);
    if (visited.contains(tag))
        return 0;
    visited.add(tag);// www .  j ava2  s  .  c om

    //open template if necessary, including memoization
    //under awareness of current plan choice
    MemoTableEntry best = null;
    boolean opened = false;
    if (memo.contains(current.getHopID())) {
        if (currentType == null) {
            best = memo.get(current.getHopID()).stream().filter(p -> p.isValid())
                    .filter(p -> hasNoRefToMaterialization(p, M, plan)).min(new BasicPlanComparator())
                    .orElse(null);
            opened = true;
        } else {
            best = memo.get(current.getHopID()).stream()
                    .filter(p -> p.type == currentType || p.type == TemplateType.CELL)
                    .filter(p -> hasNoRefToMaterialization(p, M, plan))
                    .min(Comparator.comparing(p -> 7 - ((p.type == currentType) ? 4 : 0) - p.countPlanRefs()))
                    .orElse(null);
        }
    }

    //create new cost vector if opened, initialized with write costs
    CostVector costVect = !opened ? costsCurrent
            : new CostVector(Math.max(current.getDim1(), 1) * Math.max(current.getDim2(), 1));

    //add compute costs of current operator to costs vector 
    if (partition.contains(current.getHopID()))
        costVect.computeCosts += computeCosts.get(current.getHopID());

    //process children recursively
    double costs = 0;
    for (int i = 0; i < current.getInput().size(); i++) {
        Hop c = current.getInput().get(i);
        if (best != null && best.isPlanRef(i))
            costs += rGetPlanCosts(memo, c, visited, partition, M, plan, computeCosts, costVect, best.type);
        else if (best != null && isImplicitlyFused(current, i, best.type))
            costVect.addInputSize(c.getInput().get(0).getHopID(),
                    Math.max(c.getDim1(), 1) * Math.max(c.getDim2(), 1));
        else { //include children and I/O costs
            costs += rGetPlanCosts(memo, c, visited, partition, M, plan, computeCosts, null, null);
            if (costVect != null && c.getDataType().isMatrix())
                costVect.addInputSize(c.getHopID(), Math.max(c.getDim1(), 1) * Math.max(c.getDim2(), 1));
        }
    }

    //add costs for opened fused operator
    if (partition.contains(current.getHopID())) {
        if (opened) {
            if (LOG.isTraceEnabled())
                LOG.trace("Cost vector for fused operator (hop " + current.getHopID() + "): " + costVect);
            costs += costVect.outSize * 8 / WRITE_BANDWIDTH; //time for output write
            costs += Math.max(costVect.computeCosts * costVect.getMaxInputSize() / COMPUTE_BANDWIDTH,
                    costVect.getSumInputSizes() * 8 / READ_BANDWIDTH);
        }
        //add costs for non-partition read in the middle of fused operator
        else if (hasNonPartitionConsumer(current, partition)) {
            costs += rGetPlanCosts(memo, current, visited, partition, M, plan, computeCosts, null, null);
        }
    }

    //sanity check non-negative costs
    if (costs < 0 || Double.isNaN(costs) || Double.isInfinite(costs))
        throw new RuntimeException("Wrong cost estimate: " + costs);

    return costs;
}

From source file:com.marand.thinkmed.medications.dto.report.TherapyDayReportUtils.java

private static String getQuantityDisplay(final SimpleTherapyDto order) {
    if (order instanceof ConstantSimpleTherapyDto) {
        return order.getQuantityDisplay();
    } else {/*from   ww w  . ja  v  a 2 s.c o m*/
        final StringBuilder strBuilder = new StringBuilder();
        final List<TimedSimpleDoseElementDto> timedDoseElements = ((VariableSimpleTherapyDto) order)
                .getTimedDoseElements().stream().filter(element -> element.getQuantityDisplay() != null)
                .collect(Collectors.toList());

        final boolean simpleVariable = timedDoseElements.get(0).getDate() == null;

        if (simpleVariable) {
            timedDoseElements.forEach(element -> strBuilder.append(
                    combineTimeAndQuantity(null, element.getTimeDisplay(), element.getQuantityDisplay())));
        } else {
            Collections.sort(timedDoseElements, Comparator.comparing(TimedSimpleDoseElementDto::getDate));

            DateTime currentDate = null;
            for (final TimedSimpleDoseElementDto timedDoseElement : timedDoseElements) {
                if (timedDoseElement.getDate().equals(currentDate)) {
                    strBuilder.append(combineTimeAndQuantity(null, timedDoseElement.getTimeDisplay(),
                            timedDoseElement.getQuantityDisplay()));
                } else {
                    strBuilder.append(combineTimeAndQuantity(timedDoseElement.getDate(),
                            timedDoseElement.getTimeDisplay(), timedDoseElement.getQuantityDisplay()));

                    currentDate = timedDoseElement.getDate();
                }
            }
        }

        return strBuilder.toString();
    }
}

From source file:org.languagetool.rules.spelling.SpellingCheckRule.java

@Experimental
protected List<String> reorderSuggestions(List<String> suggestions, String word) {
    // WORK IN PROGRESS
    if (languageModel == null) {
        return suggestions;
    }/*  www .j  a va  2s  .c o  m*/
    BaseLanguageModel lm = (BaseLanguageModel) languageModel;
    List<Integer> levenshteinDistances = suggestions.stream()
            .map(suggestion -> StringUtils.getLevenshteinDistance(word, suggestion))
            .collect(Collectors.toList());
    List<Long> frequencies = suggestions.stream().map(lm::getCount).collect(Collectors.toList());
    Long frequenciesSum = frequencies.stream().reduce((a, b) -> a + b).orElse(1L);
    List<Float> normalizedFrequencies = frequencies.stream().map(f -> (float) f / frequenciesSum)
            .collect(Collectors.toList());
    System.out.println("frequencies: " + frequencies + " / normalized: " + normalizedFrequencies);

    List<Pair<String, Float>> scoredSuggestions = new ArrayList<>(suggestions.size());
    for (int i = 0; i < suggestions.size(); i++) {
        float score = (1f / normalizedFrequencies.get(i)) * levenshteinDistances.get(i);
        scoredSuggestions.add(Pair.of(suggestions.get(i), score));
    }
    scoredSuggestions.sort(Comparator.comparing(Pair::getRight));

    System.out.println(
            "Before reordering: " + suggestions.subList(0, 5) + " / After: " + scoredSuggestions.subList(0, 5));

    return scoredSuggestions.stream().map(Pair::getLeft).collect(Collectors.toList());
}

From source file:nl.knaw.huygens.alexandria.lmnl.importer.LMNLImporterTest.java

private void assertActualMatchesExpected(TAGDocument actual, TAGDocument expected) {
    List<TAGMarkup> actualMarkupList = actual.getMarkupStream().collect(toList());
    List<TAGTextNode> actualTextNodeList = actual.getTextNodeStream().collect(toList());

    List<TAGMarkup> expectedMarkupList = expected.getMarkupStream().collect(toList());
    List<TAGTextNode> expectedTextNodeList = expected.getTextNodeStream().collect(toList());

    assertThat(actualTextNodeList).hasSize(expectedTextNodeList.size());
    for (int i = 0; i < expectedTextNodeList.size(); i++) {
        TAGTextNode actualTextNode = actualTextNodeList.get(i);
        TAGTextNode expectedTextNode = expectedTextNodeList.get(i);
        Comparator<TAGTextNode> textNodeComparator = Comparator.comparing(TAGTextNode::getText);
        assertThat(actualTextNode).usingComparator(textNodeComparator).isEqualTo(expectedTextNode);
    }//from   w  ww. ja  v a 2 s . c  om

    assertThat(actualMarkupList).hasSize(expectedMarkupList.size());
    for (int i = 0; i < expectedMarkupList.size(); i++) {
        TAGMarkup actualMarkup = actualMarkupList.get(i);
        TAGMarkup expectedMarkup = expectedMarkupList.get(i);
        assertThat(actualMarkup.getTag()).isEqualTo(expectedMarkup.getTag());
        Comparator<TAGMarkup> markupComparator = Comparator.comparing(TAGMarkup::getTag);
        assertThat(actualMarkup).usingComparator(markupComparator).isEqualTo(expectedMarkup);
    }

    String actualTAGML = tagmlExporter.asTAGML(actual);
    String expectedTAGML = tagmlExporter.asTAGML(expected);
    LOG.info("TAGML={}", actualTAGML);
    assertThat(actualTAGML).isEqualTo(expectedTAGML);
    // assertThat(actual).isEqualToComparingFieldByFieldRecursively(expected);
}

From source file:org.elasticsearch.xpack.core.ssl.SSLServiceTests.java

public void testReadCertificateInformation() throws Exception {
    final Path jksPath = getDataPath(
            "/org/elasticsearch/xpack/security/transport/ssl/certs/simple/testnode.jks");
    final Path p12Path = getDataPath(
            "/org/elasticsearch/xpack/security/transport/ssl/certs/simple/testnode.p12");
    final Path pemPath = getDataPath(
            "/org/elasticsearch/xpack/security/transport/ssl/certs/simple/active-directory-ca.crt");

    final MockSecureSettings secureSettings = new MockSecureSettings();
    secureSettings.setString("xpack.ssl.keystore.secure_password", "testnode");
    secureSettings.setString("xpack.ssl.truststore.secure_password", "testnode");
    secureSettings.setString("xpack.http.ssl.keystore.secure_password", "testnode");

    final Settings settings = Settings.builder().put("xpack.ssl.keystore.path", jksPath)
            .put("xpack.ssl.truststore.path", jksPath).put("xpack.http.ssl.keystore.path", p12Path)
            .put("xpack.security.authc.realms.ad.type", "ad")
            .put("xpack.security.authc.realms.ad.ssl.certificate_authorities", pemPath)
            .setSecureSettings(secureSettings).build();

    final SSLService sslService = new SSLService(settings, env);
    final List<CertificateInfo> certificates = new ArrayList<>(sslService.getLoadedCertificates());
    assertThat(certificates, iterableWithSize(10));
    Collections.sort(certificates,
            Comparator.comparing((CertificateInfo c) -> c.alias() == null ? "" : c.alias())
                    .thenComparing(CertificateInfo::path));

    final Iterator<CertificateInfo> iterator = certificates.iterator();
    CertificateInfo cert = iterator.next();
    assertThat(cert.alias(), nullValue());
    assertThat(cert.path(), equalTo(pemPath.toString()));
    assertThat(cert.format(), equalTo("PEM"));
    assertThat(cert.serialNumber(), equalTo("580db8ad52bb168a4080e1df122a3f56"));
    assertThat(cert.subjectDn(), equalTo("CN=ad-ELASTICSEARCHAD-CA, DC=ad, DC=test, DC=elasticsearch, DC=com"));
    assertThat(cert.expiry(), equalTo(DateTime.parse("2029-08-27T16:32:42Z")));
    assertThat(cert.hasPrivateKey(), equalTo(false));

    cert = iterator.next();//from w w  w  .j a v a2  s  . c o  m
    assertThat(cert.alias(), equalTo("activedir"));
    assertThat(cert.path(), equalTo(jksPath.toString()));
    assertThat(cert.format(), equalTo("jks"));
    assertThat(cert.serialNumber(), equalTo("580db8ad52bb168a4080e1df122a3f56"));
    assertThat(cert.subjectDn(), equalTo("CN=ad-ELASTICSEARCHAD-CA, DC=ad, DC=test, DC=elasticsearch, DC=com"));
    assertThat(cert.expiry(), equalTo(DateTime.parse("2029-08-27T16:32:42Z")));
    assertThat(cert.hasPrivateKey(), equalTo(false));

    cert = iterator.next();
    assertThat(cert.alias(), equalTo("mykey"));
    assertThat(cert.path(), equalTo(jksPath.toString()));
    assertThat(cert.format(), equalTo("jks"));
    assertThat(cert.serialNumber(), equalTo("3151a81eec8d4e34c56a8466a8510bcfbe63cc31"));
    assertThat(cert.subjectDn(), equalTo("CN=samba4"));
    assertThat(cert.expiry(), equalTo(DateTime.parse("2021-02-14T17:49:11.000Z")));
    assertThat(cert.hasPrivateKey(), equalTo(false));

    cert = iterator.next();
    assertThat(cert.alias(), equalTo("openldap"));
    assertThat(cert.path(), equalTo(jksPath.toString()));
    assertThat(cert.format(), equalTo("jks"));
    assertThat(cert.serialNumber(), equalTo("d3850b2b1995ad5f"));
    assertThat(cert.subjectDn(),
            equalTo("CN=OpenLDAP, OU=Elasticsearch, O=Elastic, L=Mountain View, ST=CA, C=US"));
    assertThat(cert.expiry(), equalTo(DateTime.parse("2027-07-23T16:41:14Z")));
    assertThat(cert.hasPrivateKey(), equalTo(false));

    cert = iterator.next();
    assertThat(cert.alias(), equalTo("testclient"));
    assertThat(cert.path(), equalTo(jksPath.toString()));
    assertThat(cert.format(), equalTo("jks"));
    assertThat(cert.serialNumber(), equalTo("b9d497f2924bbe29"));
    assertThat(cert.subjectDn(), equalTo("CN=Elasticsearch Test Client, OU=elasticsearch, O=org"));
    assertThat(cert.expiry(), equalTo(DateTime.parse("2019-09-22T18:52:55Z")));
    assertThat(cert.hasPrivateKey(), equalTo(false));

    cert = iterator.next();
    assertThat(cert.alias(), equalTo("testnode-client-profile"));
    assertThat(cert.path(), equalTo(jksPath.toString()));
    assertThat(cert.format(), equalTo("jks"));
    assertThat(cert.serialNumber(), equalTo("c0ea4216e8ff0fd8"));
    assertThat(cert.subjectDn(), equalTo("CN=testnode-client-profile"));
    assertThat(cert.expiry(), equalTo(DateTime.parse("2019-09-22T18:52:56Z")));
    assertThat(cert.hasPrivateKey(), equalTo(false));

    cert = iterator.next();
    assertThat(cert.alias(), equalTo("testnode_dsa"));
    assertThat(cert.path(), equalTo(jksPath.toString()));
    assertThat(cert.format(), equalTo("jks"));
    assertThat(cert.serialNumber(), equalTo("223c736a"));
    assertThat(cert.subjectDn(), equalTo("CN=Elasticsearch Test Node"));
    assertThat(cert.expiry(), equalTo(DateTime.parse("2045-10-02T09:43:18.000Z")));
    assertThat(cert.hasPrivateKey(), equalTo(true));

    cert = iterator.next();
    assertThat(cert.alias(), equalTo("testnode_ec"));
    assertThat(cert.path(), equalTo(jksPath.toString()));
    assertThat(cert.format(), equalTo("jks"));
    assertThat(cert.serialNumber(), equalTo("7268203b"));
    assertThat(cert.subjectDn(), equalTo("CN=Elasticsearch Test Node"));
    assertThat(cert.expiry(), equalTo(DateTime.parse("2045-10-02T09:36:10.000Z")));
    assertThat(cert.hasPrivateKey(), equalTo(true));

    cert = iterator.next();
    assertThat(cert.alias(), equalTo("testnode_rsa"));
    assertThat(cert.path(), equalTo(jksPath.toString()));
    assertThat(cert.format(), equalTo("jks"));
    assertThat(cert.serialNumber(), equalTo("b8b96c37e332cccb"));
    assertThat(cert.subjectDn(), equalTo("CN=Elasticsearch Test Node, OU=elasticsearch, O=org"));
    assertThat(cert.expiry(), equalTo(DateTime.parse("2019-09-22T18:52:57.000Z")));
    assertThat(cert.hasPrivateKey(), equalTo(true));

    cert = iterator.next();
    assertThat(cert.alias(), equalTo("testnode_rsa"));
    assertThat(cert.path(), equalTo(p12Path.toString()));
    assertThat(cert.format(), equalTo("PKCS12"));
    assertThat(cert.serialNumber(), equalTo("b8b96c37e332cccb"));
    assertThat(cert.subjectDn(), equalTo("CN=Elasticsearch Test Node, OU=elasticsearch, O=org"));
    assertThat(cert.expiry(), equalTo(DateTime.parse("2019-09-22T18:52:57Z")));
    assertThat(cert.hasPrivateKey(), equalTo(true));

    assertFalse(iterator.hasNext());
}

From source file:sx.blah.discord.handle.impl.obj.Guild.java

@Override
public void reorderRoles(IRole... rolesInOrder) {
    if (rolesInOrder.length != getRoles().size())
        throw new DiscordException(
                "The number of roles to reorder does not equal the number of available roles!");

    PermissionUtils.requirePermissions(this, client.getOurUser(), Permissions.MANAGE_ROLES);

    int usersHighest = getRolesForUser(client.getOurUser()).stream().map(IRole::getPosition)
            .max(Comparator.comparing(Function.identity())).orElse(-1);

    ReorderRolesRequest[] request = new ReorderRolesRequest[roles.size()];

    for (int i = 0; i < roles.size(); i++) {
        IRole role = rolesInOrder[i];// w  w  w. j av  a  2s  .  com

        int newPosition = role.getPosition();
        int oldPosition = getRoleByID(role.getLongID()).getPosition();
        if (newPosition != oldPosition && oldPosition >= usersHighest) { // If the position was changed and the user doesn't have permission to change it.
            throw new MissingPermissionsException(
                    "Cannot edit the position of a role higher than or equal to your own.",
                    EnumSet.noneOf(Permissions.class));
        } else {
            request[i] = new ReorderRolesRequest(role.getStringID(), i);
        }
    }

    ((DiscordClientImpl) client).REQUESTS.PATCH.makeRequest(DiscordEndpoints.GUILDS + getStringID() + "/roles",
            request);
}

From source file:org.cgiar.ccafs.marlo.action.annualReport.IndicatorsAction.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();

    // Verify if is Influence or Control section
    String[] actionParts = this.getActionName().split("/");
    if (actionParts.length > 0) {
        String action = actionParts[1];
        if (action.equals(ReportSynthesisSectionStatusEnum.INFLUENCE.getStatus())) {
            isInfluence = true;//from  w  ww  .  ja v a  2  s  .  com
        } else if (action.equals(ReportSynthesisSectionStatusEnum.CONTROL.getStatus())) {
            isInfluence = false;
        }
    }

    // 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;
            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) {
        // reportSynthesisPMU: Used to calculate FLagships values
        LiaisonInstitution pmuInstitution = loggedCrp.getLiaisonInstitutions().stream()
                .filter(c -> c.getCrpProgram() == null && c.getAcronym().equals("PMU"))
                .collect(Collectors.toList()).get(0);
        reportSynthesisPMU = reportSynthesisManager.findSynthesis(phase.getId(), pmuInstitution.getId());

        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.getReportSynthesisIndicatorGeneral() == null) {
                ReportSynthesisIndicatorGeneral indicatorGeneral = new ReportSynthesisIndicatorGeneral();
                // create one to one relation
                reportSynthesis.setReportSynthesisIndicatorGeneral(indicatorGeneral);
                indicatorGeneral.setReportSynthesis(reportSynthesis);
                // save the changes
                reportSynthesis = reportSynthesisManager.saveReportSynthesis(reportSynthesis);
            }
            if (this.isPMU()) {
                List<ReportSynthesisIndicator> reportSynthesisIndicators = new ArrayList<>();
                if (isInfluence) {
                    reportSynthesisIndicators = reportSynthesisIndicatorManager.getIndicatorsByType(
                            reportSynthesis, APConstants.REP_IND_SYNTHESIS_INDICATOR_TYPE_INFLUENCE);
                } else {
                    reportSynthesisIndicators = reportSynthesisIndicatorManager.getIndicatorsByType(
                            reportSynthesis, APConstants.REP_IND_SYNTHESIS_INDICATOR_TYPE_CONTROL);
                }

                if (reportSynthesisIndicators != null && !reportSynthesisIndicators.isEmpty()) {
                    reportSynthesis.getReportSynthesisIndicatorGeneral()
                            .setSynthesisIndicators(new ArrayList<>(reportSynthesisIndicators));
                } else {
                    reportSynthesis.getReportSynthesisIndicatorGeneral()
                            .setSynthesisIndicators(new ArrayList<>());
                    List<RepIndSynthesisIndicator> repIndSynthesisIndicator = new ArrayList<>();
                    if (isInfluence) {
                        repIndSynthesisIndicator = repIndSynthesisIndicatorManager.findAll().stream()
                                .filter(i -> i.isMarlo() && i.getType()
                                        .equals(APConstants.REP_IND_SYNTHESIS_INDICATOR_TYPE_INFLUENCE))
                                .sorted((i1, i2) -> i1.getIndicator().compareTo(i2.getIndicator()))
                                .collect(Collectors.toList());
                    } else {
                        repIndSynthesisIndicator = repIndSynthesisIndicatorManager.findAll().stream()
                                .filter(i -> i.isMarlo() && i.getType()
                                        .equals(APConstants.REP_IND_SYNTHESIS_INDICATOR_TYPE_CONTROL))
                                .sorted((i1, i2) -> i1.getIndicator().compareTo(i2.getIndicator()))
                                .collect(Collectors.toList());
                    }

                    for (RepIndSynthesisIndicator synthesisIndicator : repIndSynthesisIndicator) {
                        ReportSynthesisIndicator reportSynthesisIndicator = new ReportSynthesisIndicator();
                        reportSynthesisIndicator.setRepIndSynthesisIndicator(synthesisIndicator);
                        reportSynthesis.getReportSynthesisIndicatorGeneral().getSynthesisIndicators()
                                .add(reportSynthesisIndicator);
                    }

                }
            }
        }
    }

    // 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()) {
        if (reportSynthesisPMU != null) {
            if (reportSynthesisPMU.getReportSynthesisIndicatorGeneral() != null) {
                List<ReportSynthesisIndicator> reportSynthesisIndicators = new ArrayList<>();

                if (isInfluence) {
                    reportSynthesisIndicators = reportSynthesisIndicatorManager.getIndicatorsByType(
                            reportSynthesisPMU, APConstants.REP_IND_SYNTHESIS_INDICATOR_TYPE_INFLUENCE);
                } else {
                    reportSynthesisIndicators = reportSynthesisIndicatorManager.getIndicatorsByType(
                            reportSynthesisPMU, APConstants.REP_IND_SYNTHESIS_INDICATOR_TYPE_CONTROL);
                }

                if (reportSynthesisIndicators != null && !reportSynthesisIndicators.isEmpty()) {
                    reportSynthesis.getReportSynthesisIndicatorGeneral()
                            .setSynthesisIndicators(reportSynthesisIndicators);
                }
            }
        }
    }
    // Informative Tables/Charts
    if (isInfluence) {
        // Chart: Studies by organization type
        organizationTypeByStudiesDTOs = repIndOrganizationTypeManager.getOrganizationTypesByStudies(phase);
        // Table: Outcomes/Impacts involved in policy/investments
        projectExpectedStudies = projectExpectedStudyManager.getStudiesByPhase(phase);
        for (ProjectExpectedStudy projectExpectedStudy : projectExpectedStudies) {
            projectExpectedStudy.getProjectExpectedStudyInfo(phase);
        }
    } else {
        // Table: Table D-2: List of CRP Innovations in 2017
        projectInnovationInfos = projectInnovationInfoManager.getProjectInnovationInfoByPhase(phase);
        // Innovations by stage
        innovationsByStageDTO = repIndStageInnovationManager.getInnovationsByStageDTO(phase);

        // Table G: Projects Key Partnerships
        projectPartnerPartnerships = projectPartnerPartnershipManager
                .getProjectPartnerPartnershipByPhase(phase);
        if (projectPartnerPartnerships != null && !projectPartnerPartnerships.isEmpty()) {
            for (ProjectPartnerPartnership projectPartnerPartnership : projectPartnerPartnerships) {
                List<ProjectPartnerPartnershipResearchPhase> projectPartnerPartnershipResearchPhases = projectPartnerPartnership
                        .getProjectPartnerPartnershipResearchPhases().stream().filter(pr -> pr.isActive())
                        .sorted((p1, p2) -> p1.getRepIndPhaseResearchPartnership().getName()
                                .compareTo(p2.getRepIndPhaseResearchPartnership().getName()))
                        .collect(Collectors.toList());
                projectPartnerPartnership.setPartnershipResearchPhases(projectPartnerPartnershipResearchPhases);
            }
        }
        // Chart: Partnerships by Partner type
        partnershipsByRepIndOrganizationTypeDTOs = repIndOrganizationTypeManager
                .getPartnershipsByRepIndOrganizationTypeDTO(projectPartnerPartnerships);
        // Chart: Partnerships by Geographic Scope
        partnershipsByGeographicScopeDTO = repIndGeographicScopeManager
                .getPartnershipsByGeographicScopeDTO(projectPartnerPartnerships);
        // Chart: Partnerships by Phase
        partnershipsByPhaseDTO = repIndPhaseResearchPartnershipManager
                .getPartnershipsByPhaseDTO(projectPartnerPartnerships);

        // Deliverables Participants
        deliverableParticipants = deliverableParticipantManager.getDeliverableParticipantByPhase(phase);
        Double totalFemales = new Double(0);
        for (DeliverableParticipant deliverableParticipant : deliverableParticipants) {
            // Total Participants
            if (deliverableParticipant.getParticipants() != null) {
                totalParticipants += deliverableParticipant.getParticipants();
            }
            if (deliverableParticipant.getFemales() != null) {
                totalFemales += deliverableParticipant.getFemales();
            }

            // Total Formal Training
            if (deliverableParticipant.getRepIndTypeActivity() != null
                    && deliverableParticipant.getRepIndTypeActivity().getName()
                            .contains(APConstants.REP_IND_SYNTHESIS_TYPE_ACTIVITY_FORMAL_TRAINING)) {
                totalParticipantFormalTraining += deliverableParticipant.getParticipants();
            }
        }
        // Percentage female
        percentageFemales = Math.round(((totalFemales * 100) / totalParticipants) * 100) / 100.0;

        // Deliverables of Journal Articles type
        DeliverableType deliverableType = deliverableTypeManager.getDeliverableTypeById(63);
        deliverableInfos = deliverableInfoManager.getDeliverablesInfoByType(phase, deliverableType);

        for (DeliverableInfo deliverableInfo : deliverableInfos) {
            // Load Disseminations
            List<DeliverableDissemination> deliverableDisseminations = deliverableInfo.getDeliverable()
                    .getDeliverableDisseminations().stream()
                    .filter(dd -> dd.isActive() && dd.getPhase() != null && dd.getPhase().equals(phase))
                    .collect(Collectors.toList());
            if (deliverableDisseminations != null && !deliverableDisseminations.isEmpty()) {
                deliverableInfo.getDeliverable().setDissemination(deliverableDisseminations.get(0));
                if (deliverableInfo.getDeliverable().getDissemination().getIsOpenAccess() != null) {
                    // Journal Articles by Open Access
                    if (deliverableInfo.getDeliverable().getDissemination().getIsOpenAccess()) {
                        totalOpenAccess++;
                    } else {
                        totalLimited++;
                    }
                } else {
                    totalLimited++;
                }
            } else {
                totalLimited++;
            }

            // Load Publications
            List<DeliverablePublicationMetadata> deliverablePublicationMetadatas = deliverableInfo
                    .getDeliverable().getDeliverablePublicationMetadatas().stream()
                    .filter(dp -> dp.isActive() && dp.getPhase() != null && dp.getPhase().equals(phase))
                    .collect(Collectors.toList());
            if (deliverablePublicationMetadatas != null && !deliverablePublicationMetadatas.isEmpty()) {
                deliverableInfo.getDeliverable().setPublication(deliverablePublicationMetadatas.get(0));
                // Journal Articles by ISI status
                if (deliverableInfo.getDeliverable().getPublication().getIsiPublication() != null) {
                    if (deliverableInfo.getDeliverable().getPublication().getIsiPublication()) {
                        totalIsis++;
                    } else {
                        totalNoIsis++;
                    }
                } else {
                    totalNoIsis++;
                }
            } else {
                totalNoIsis++;
            }

            // Load Partnerships
            List<DeliverablePartnership> deliverablePartnerships = deliverableInfo.getDeliverable()
                    .getDeliverablePartnerships().stream()
                    .filter(dp -> dp.isActive() && dp.getPhase() != null && dp.getPhase().equals(phase)
                            && dp.getPartnerType()
                                    .equals(DeliverablePartnershipTypeEnum.RESPONSIBLE.getValue()))
                    .collect(Collectors.toList());
            if (deliverablePartnerships != null && !deliverablePartnerships.isEmpty()) {
                deliverableInfo.getDeliverable().setResponsiblePartner(deliverablePartnerships.get(0));
            }
        }
    }

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

    if (this.isHttpPost()) {
        if (reportSynthesis.getReportSynthesisIndicatorGeneral().getSynthesisIndicators() != null) {
            reportSynthesis.getReportSynthesisIndicatorGeneral().getSynthesisIndicators().clear();
        }
    }
}

From source file:com.cloudbees.jenkins.plugins.bitbucket.client.BitbucketCloudApiClient.java

/**
 * The role parameter only makes sense when the request is authenticated, so
 * if there is no auth information ({@link #authenticator}) the role will be omitted.
 *//*from w w w  .  j a v  a2 s.c o m*/
@NonNull
@Override
public List<BitbucketCloudRepository> getRepositories(@CheckForNull UserRoleInRepository role)
        throws InterruptedException, IOException {
    StringBuilder cacheKey = new StringBuilder();
    cacheKey.append(owner);

    if (authenticator != null) {
        cacheKey.append("::").append(authenticator.getId());
    } else {
        cacheKey.append("::<anonymous>");
    }

    final UriTemplate template = UriTemplate.fromTemplate(V2_API_BASE_URL + "{/owner}{?role,page,pagelen}")
            .set("owner", owner).set("pagelen", 50);
    if (role != null && authenticator != null) {
        template.set("role", role.getId());
        cacheKey.append("::").append(role.getId());
    }
    Callable<List<BitbucketCloudRepository>> request = () -> {
        List<BitbucketCloudRepository> repositories = new ArrayList<>();
        Integer pageNumber = 1;
        String url, response;
        PaginatedBitbucketRepository page;
        do {
            response = getRequest(url = template.set("page", pageNumber).expand());
            try {
                page = JsonParser.toJava(response, PaginatedBitbucketRepository.class);
                repositories.addAll(page.getValues());
            } catch (IOException e) {
                throw new IOException("I/O error when parsing response from URL: " + url, e);
            }
            pageNumber++;
        } while (page.getNext() != null);
        repositories.sort(Comparator.comparing(BitbucketCloudRepository::getRepositoryName));
        return repositories;
    };
    try {
        if (enableCache) {
            return cachedRepositories.get(cacheKey.toString(), request);
        } else {
            return request.call();
        }
    } catch (Exception ex) {
        throw new IOException("Error while loading repositories from cache", ex);
    }
}

From source file:org.cgiar.ccafs.marlo.action.annualReport.CrossCuttingDimensionAction.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  2 s. co m*/
            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);

        // Fill Flagship Innovations and Assets
        if (this.isFlagship()) {
            this.flagshipSelectTables(phase.getId(), liaisonInstitution);
        }

        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.getReportSynthesisCrossCuttingDimension() == null) {
                ReportSynthesisCrossCuttingDimension cuttingDimension = new ReportSynthesisCrossCuttingDimension();
                // create one to one relation
                reportSynthesis.setReportSynthesisCrossCuttingDimension(cuttingDimension);
                cuttingDimension.setReportSynthesis(reportSynthesis);
                // save the changes
                reportSynthesis = reportSynthesisManager.saveReportSynthesis(reportSynthesis);
            }

            if (this.isFlagship()) {

                // Project Innovations
                reportSynthesis.getReportSynthesisCrossCuttingDimension().setInnovations(new ArrayList<>());
                if (reportSynthesis.getReportSynthesisCrossCuttingDimension()
                        .getReportSynthesisCrossCuttingDimensionInnovations() != null
                        && !reportSynthesis.getReportSynthesisCrossCuttingDimension()
                                .getReportSynthesisCrossCuttingDimensionInnovations().isEmpty()) {
                    for (ReportSynthesisCrossCuttingDimensionInnovation dimensionInnovation : reportSynthesis
                            .getReportSynthesisCrossCuttingDimension()
                            .getReportSynthesisCrossCuttingDimensionInnovations().stream()
                            .filter(i -> i.isActive()).collect(Collectors.toList())) {
                        reportSynthesis.getReportSynthesisCrossCuttingDimension().getInnovations()
                                .add(dimensionInnovation.getProjectInnovation());
                    }
                }

                // Deliverable Intellectual Assets
                reportSynthesis.getReportSynthesisCrossCuttingDimension().setAssets(new ArrayList<>());
                if (reportSynthesis.getReportSynthesisCrossCuttingDimension()
                        .getReportSynthesisCrossCuttingDimensionAssets() != null
                        && !reportSynthesis.getReportSynthesisCrossCuttingDimension()
                                .getReportSynthesisCrossCuttingDimensionAssets().isEmpty()) {
                    for (ReportSynthesisCrossCuttingDimensionAsset dimensionAsset : reportSynthesis
                            .getReportSynthesisCrossCuttingDimension()
                            .getReportSynthesisCrossCuttingDimensionAssets().stream().filter(a -> a.isActive())
                            .collect(Collectors.toList())) {
                        reportSynthesis.getReportSynthesisCrossCuttingDimension().getAssets()
                                .add(dimensionAsset.getDeliverableIntellectualAsset());
                    }
                }
            }
        }
    }

    // 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));

    if (this.isPMU()) {

        // Flagship Cross Cutting Dimensions Synthesis progress
        flagshipCCDimensions = reportSynthesisCrossCuttingDimensionManager
                .getFlagshipCCDimensions(liaisonInstitutions, phase.getId());

        // Table D-2 Lof of Crp Innovations
        flagshipPlannedInnovations = reportSynthesisCrossCuttingDimensionManager.getPlannedInnovationList(
                liaisonInstitutions, phase.getId(), loggedCrp, this.liaisonInstitution);

        // Table E Intellectual Assets
        flagshipPlannedAssets = reportSynthesisCrossCuttingDimensionManager
                .getPlannedAssetsList(liaisonInstitutions, phase.getId(), loggedCrp, this.liaisonInstitution);

    }

    // Setup Table C
    tableC = reportSynthesisCrossCuttingDimensionManager.getTableC(phase, loggedCrp);
    deliverableList = tableC.getDeliverableList();

    // 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()));

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

    if (this.isHttpPost()) {
        if (reportSynthesis.getReportSynthesisCrossCuttingDimension().getPlannedAssets() != null) {
            reportSynthesis.getReportSynthesisCrossCuttingDimension().getPlannedAssets().clear();
        }

        if (reportSynthesis.getReportSynthesisCrossCuttingDimension().getPlannedInnovations() != null) {
            reportSynthesis.getReportSynthesisCrossCuttingDimension().getPlannedInnovations().clear();
        }
    }
}