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.kitodo.production.services.data.ProcessService.java

/**
 * Filter and sort after creation date list of process properties for
 * correction and solution messages./*from w w  w. java2s  .  co  m*/
 *
 * @return list of ProcessProperty objects
 */
public List<PropertyDTO> getSortedCorrectionSolutionMessages(ProcessDTO process) {
    List<PropertyDTO> filteredList = filterForCorrectionSolutionMessages(process.getProperties());

    if (filteredList.size() > 1) {
        filteredList.sort(Comparator.comparing(PropertyDTO::getCreationDate,
                Comparator.nullsFirst(Comparator.naturalOrder())));
    }

    return filteredList;
}

From source file:org.optaplanner.core.impl.domain.solution.descriptor.SolutionDescriptor.java

private void determineGlobalShadowOrder() {
    // Topological sorting with Kahn's algorithm
    List<Pair<ShadowVariableDescriptor<Solution_>, Integer>> pairList = new ArrayList<>();
    Map<ShadowVariableDescriptor<Solution_>, Pair<ShadowVariableDescriptor<Solution_>, Integer>> shadowToPairMap = new HashMap<>();
    for (EntityDescriptor<Solution_> entityDescriptor : entityDescriptorMap.values()) {
        for (ShadowVariableDescriptor<Solution_> shadow : entityDescriptor
                .getDeclaredShadowVariableDescriptors()) {
            int sourceSize = shadow.getSourceVariableDescriptorList().size();
            Pair<ShadowVariableDescriptor<Solution_>, Integer> pair = MutablePair.of(shadow, sourceSize);
            pairList.add(pair);//  w w  w. ja  va  2  s.  c  o  m
            shadowToPairMap.put(shadow, pair);
        }
    }
    for (EntityDescriptor<Solution_> entityDescriptor : entityDescriptorMap.values()) {
        for (GenuineVariableDescriptor<Solution_> genuine : entityDescriptor
                .getDeclaredGenuineVariableDescriptors()) {
            for (ShadowVariableDescriptor<Solution_> sink : genuine.getSinkVariableDescriptorList()) {
                Pair<ShadowVariableDescriptor<Solution_>, Integer> sinkPair = shadowToPairMap.get(sink);
                sinkPair.setValue(sinkPair.getValue() - 1);
            }
        }
    }
    int globalShadowOrder = 0;
    while (!pairList.isEmpty()) {
        pairList.sort(Comparator.comparingInt(Pair::getValue));
        Pair<ShadowVariableDescriptor<Solution_>, Integer> pair = pairList.remove(0);
        ShadowVariableDescriptor<Solution_> shadow = pair.getKey();
        if (pair.getValue() != 0) {
            if (pair.getValue() < 0) {
                throw new IllegalStateException("Impossible state because the shadowVariable ("
                        + shadow.getSimpleEntityAndVariableName()
                        + ") can not be used more as a sink than it has sources.");
            }
            throw new IllegalStateException("There is a cyclic shadow variable path"
                    + " that involves the shadowVariable (" + shadow.getSimpleEntityAndVariableName()
                    + ") because it must be later than its sources (" + shadow.getSourceVariableDescriptorList()
                    + ") and also earlier than its sinks (" + shadow.getSinkVariableDescriptorList() + ").");
        }
        for (ShadowVariableDescriptor<Solution_> sink : shadow.getSinkVariableDescriptorList()) {
            Pair<ShadowVariableDescriptor<Solution_>, Integer> sinkPair = shadowToPairMap.get(sink);
            sinkPair.setValue(sinkPair.getValue() - 1);
        }
        shadow.setGlobalShadowOrder(globalShadowOrder);
        globalShadowOrder++;
    }
}

From source file:org.cgiar.ccafs.marlo.action.publications.PublicationAction.java

@Override
public void prepare() throws Exception {

    loggedCrp = (GlobalUnit) this.getSession().get(APConstants.SESSION_CRP);
    loggedCrp = crpManager.getGlobalUnitById(loggedCrp.getId());
    try {/*from w ww.j  av a  2s .  c  o  m*/
        deliverableID = Long.parseLong(
                StringUtils.trim(this.getRequest().getParameter(APConstants.PROJECT_DELIVERABLE_REQUEST_ID)));
    } catch (Exception e) {
        LOG.error("unable to parse deliverableID", e);
        /**
         * Original code swallows the exception and didn't even log it. Now we at least log it,
         * but we need to revisit to see if we should continue processing or re-throw the exception.
         */
    }

    if (this.getRequest().getParameter(APConstants.TRANSACTION_ID) != null) {

        transaction = StringUtils.trim(this.getRequest().getParameter(APConstants.TRANSACTION_ID));
        Deliverable history = (Deliverable) auditLogManager.getHistory(transaction);

        if (history != null) {
            deliverable = history;
        } else {
            this.transaction = null;
            this.setTransaction("-1");
        }
    } else {
        deliverable = deliverableManager.getDeliverableById(deliverableID);
    }

    if (deliverable != null) {

        Path path = this.getAutoSaveFilePath();

        if (path.toFile().exists() && this.getCurrentUser().isAutoSave()) {

            BufferedReader reader = null;
            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();

            deliverable = (Deliverable) autoSaveReader.readFromJson(jReader);
            deliverable.setPhase(deliverableManager.getDeliverableById(deliverable.getId()).getPhase());

            if (metadataElementManager.findAll() != null) {
                deliverable.setMetadata(new ArrayList<>(metadataElementManager.findAll()));
            }
            deliverable.getDeliverableInfo(deliverable.getPhase());
            if (deliverable.getFundingSources() != null) {
                for (DeliverableFundingSource fundingSource : deliverable.getFundingSources()) {
                    if (fundingSource != null && fundingSource.getFundingSource() != null) {
                        fundingSource.setFundingSource(fundingSourceManager
                                .getFundingSourceById(fundingSource.getFundingSource().getId()));
                        fundingSource.getFundingSource().getFundingSourceInfo(deliverable.getPhase());
                    }
                }
            }

            if (deliverable.getCrps() != null) {
                for (DeliverableCrp deliverableCrp : deliverable.getCrps()) {
                    if (deliverableCrp != null) {
                        if (deliverableCrp.getCrpProgram() == null
                                || deliverableCrp.getCrpProgram().getId() == null
                                || deliverableCrp.getCrpProgram().getId().intValue() == -1) {
                            if (deliverableCrp.getGlobalUnit() != null
                                    && deliverableCrp.getGlobalUnit().getId() != null
                                    && deliverableCrp.getGlobalUnit().getId().intValue() != -1) {
                                deliverableCrp.setGlobalUnit(
                                        crpManager.getGlobalUnitById(deliverableCrp.getGlobalUnit().getId()));
                            }
                        } else {
                            deliverableCrp.setCrpProgram(crpProgramManager
                                    .getCrpProgramById(deliverableCrp.getCrpProgram().getId()));
                        }
                    }
                }
            }

            if (deliverable.getLeaders() != null) {
                for (DeliverableLeader deliverableLeader : deliverable.getLeaders()) {
                    if (deliverableLeader != null) {
                        deliverableLeader.setInstitution(institutionManager
                                .getInstitutionById(deliverableLeader.getInstitution().getId()));

                    }
                }
            }

            List<DeliverableProgram> programs = new ArrayList<>();
            if (deliverable.getFlagshipValue() != null) {
                for (String programID : deliverable.getFlagshipValue().trim().replace("[", "").replace("]", "")
                        .split(",")) {
                    try {
                        DeliverableProgram deliverableProgram = new DeliverableProgram();
                        CrpProgram program = crpProgramManager
                                .getCrpProgramById(Long.parseLong(programID.trim()));
                        deliverableProgram.setDeliverable(deliverable);
                        deliverableProgram.setCrpProgram(program);
                        programs.add(deliverableProgram);
                    } catch (Exception e) {
                        LOG.error("unable to add deliverableProgram to programs list", e);
                        /**
                         * Original code swallows the exception and didn't even log it. Now we at least log it,
                         * but we need to revisit to see if we should continue processing or re-throw the exception.
                         */
                    }
                }
            }

            List<DeliverableProgram> regions = new ArrayList<>();
            if (deliverable.getRegionsValue() != null) {
                for (String programID : deliverable.getRegionsValue().trim().replace("[", "").replace("]", "")
                        .split(",")) {
                    try {
                        DeliverableProgram deliverableProgram = new DeliverableProgram();
                        CrpProgram program = crpProgramManager
                                .getCrpProgramById(Long.parseLong(programID.trim()));
                        deliverableProgram.setDeliverable(deliverable);
                        deliverableProgram.setCrpProgram(program);
                        regions.add(deliverableProgram);
                    } catch (Exception e) {
                        LOG.error("unable to add delverable program to regions list", e);
                        /**
                         * Original code swallows the exception and didn't even log it. Now we at least log it,
                         * but we need to revisit to see if we should continue processing or re-throw the exception.
                         */
                    }
                }
            }
            deliverable.setPrograms(programs);
            deliverable.setRegions(regions);

            String type = deliverable.getDissemination().getType();
            if (type != null) {
                switch (type) {
                case "intellectualProperty":
                    deliverable.getDissemination().setIntellectualProperty(true);
                    break;
                case "limitedExclusivity":
                    deliverable.getDissemination().setLimitedExclusivity(true);
                    break;
                case "restrictedUseAgreement":
                    deliverable.getDissemination().setRestrictedUseAgreement(true);
                    break;
                case "effectiveDateRestriction":
                    deliverable.getDissemination().setEffectiveDateRestriction(true);
                    break;
                case "notDisseminated":
                    deliverable.getDissemination().setNotDisseminated(true);
                default:
                    break;
                }
            }
            if (deliverable.getDeliverableParticipant() != null) {
                DeliverableParticipant deliverableParticipant = deliverable.getDeliverableParticipant();
                if (deliverableParticipant.getParticipantLocationsIsosText() != null) {
                    String[] locationsIsos = deliverableParticipant.getParticipantLocationsIsosText()
                            .replace("[", "").replace("]", "").split(",");
                    List<String> locations = new ArrayList<>();
                    for (String value : Arrays.asList(locationsIsos)) {
                        locations.add(value.trim());
                    }
                    deliverableParticipant.setParticipantLocationsIsos(locations);
                }
            }
            this.setDraft(true);

        } else {
            deliverable.getDeliverableInfo(deliverable.getPhase());

            deliverable.setFundingSources(deliverable.getDeliverableFundingSources().stream().filter(
                    c -> c.isActive() && c.getPhase() != null && c.getPhase().equals(deliverable.getPhase()))
                    .collect(Collectors.toList()));
            for (DeliverableFundingSource deliverableFundingSource : deliverable.getFundingSources()) {

                deliverableFundingSource.setFundingSource(fundingSourceManager
                        .getFundingSourceById(deliverableFundingSource.getFundingSource().getId()));
                deliverableFundingSource.getFundingSource().setFundingSourceInfo(deliverableFundingSource
                        .getFundingSource().getFundingSourceInfo(deliverable.getPhase()));
                if (deliverableFundingSource.getFundingSource().getFundingSourceInfo() == null) {
                    deliverableFundingSource.getFundingSource().setFundingSourceInfo(deliverableFundingSource
                            .getFundingSource().getFundingSourceInfoLast(deliverable.getPhase()));
                }
            }
            deliverable.setGenderLevels(deliverable.getDeliverableGenderLevels().stream()
                    .filter(c -> c.isActive() && c.getPhase().equals(deliverable.getPhase()))
                    .collect(Collectors.toList()));

            deliverable.setLeaders(deliverable.getDeliverableLeaders().stream()
                    .filter(dl -> dl.isActive() && dl.getPhase().equals(deliverable.getPhase()))
                    .sorted((l1, l2) -> l1.getInstitution().getName().compareTo(l2.getInstitution().getName()))
                    .collect(Collectors.toList()));
            List<DeliverableProgram> deliverablePrograms = deliverable.getDeliverablePrograms().stream()
                    .filter(c -> c.isActive() && c.getPhase().equals(deliverable.getPhase()))
                    .collect(Collectors.toList());

            deliverable.setPrograms(deliverablePrograms.stream().filter(c -> c.isActive()
                    && c.getCrpProgram().getProgramType() == ProgramType.FLAGSHIP_PROGRAM_TYPE.getValue())
                    .sorted((f1, f2) -> f1.getCrpProgram().getAcronym()
                            .compareTo(f2.getCrpProgram().getAcronym()))
                    .collect(Collectors.toList()));
            deliverable.setRegions(deliverablePrograms.stream().filter(c -> c.isActive()
                    && c.getCrpProgram().getProgramType() == ProgramType.REGIONAL_PROGRAM_TYPE.getValue())
                    .sorted((r1, r2) -> r1.getCrpProgram().getAcronym()
                            .compareTo(r2.getCrpProgram().getAcronym()))
                    .collect(Collectors.toList()));

            if (deliverable.getDeliverableMetadataElements() != null) {
                deliverable.setMetadataElements(new ArrayList<>(deliverable.getDeliverableMetadataElements()
                        .stream().filter(c -> c.isActive() && c.getPhase().equals(deliverable.getPhase()))
                        .collect(Collectors.toList())));
            }

            if (deliverable.getDeliverableDisseminations() != null) {
                deliverable.setDisseminations(new ArrayList<>(deliverable.getDeliverableDisseminations()
                        .stream().filter(c -> c.isActive() && c.getPhase().equals(deliverable.getPhase()))
                        .collect(Collectors.toList())));
                if (deliverable.getDisseminations().size() > 0) {
                    deliverable.setDissemination(deliverable.getDisseminations().get(0));
                } else {
                    deliverable.setDissemination(new DeliverableDissemination());
                }
            }

            if (deliverable.getDeliverablePublicationMetadatas() != null) {
                deliverable.setPublicationMetadatas(
                        new ArrayList<>(deliverable.getDeliverablePublicationMetadatas().stream()
                                .filter(c -> c.isActive() && c.getPhase().equals(deliverable.getPhase()))
                                .collect(Collectors.toList())));
            }
            if (!deliverable.getPublicationMetadatas().isEmpty()) {
                deliverable.setPublication(deliverable.getPublicationMetadatas().get(0));
            }

            if (deliverable.getDeliverableDataSharings() != null) {
                deliverable.setDataSharing(new ArrayList<>(deliverable.getDeliverableDataSharings().stream()
                        .filter(c -> c.getPhase().equals(deliverable.getPhase()))
                        .collect(Collectors.toList())));
            }

            deliverable.setUsers(deliverable.getDeliverableUsers().stream()
                    .filter(c -> c.isActive() && c.getPhase().equals(deliverable.getPhase()))
                    .collect(Collectors.toList()));
            deliverable.setCrps(deliverable.getDeliverableCrps().stream()
                    .filter(c -> c.isActive() && c.getPhase().equals(deliverable.getPhase()))
                    .collect(Collectors.toList()));

            if (deliverable.getDeliverableIntellectualAssets() != null) {
                List<DeliverableIntellectualAsset> intellectualAssets = deliverable
                        .getDeliverableIntellectualAssets().stream()
                        .filter(c -> c.isActive() && c.getPhase().equals(deliverable.getPhase()))
                        .collect(Collectors.toList());

                if (intellectualAssets.size() > 0) {
                    deliverable.setIntellectualAsset(intellectualAssets.get(0));
                    if (this.transaction != null && !this.transaction.equals("-1")) {
                        if (deliverable.getIntellectualAsset().getFillingType() != null
                                && deliverable.getIntellectualAsset().getFillingType().getId() != null) {
                            deliverable.getIntellectualAsset()
                                    .setFillingType(repIndFillingTypeManager.getRepIndFillingTypeById(
                                            deliverable.getIntellectualAsset().getFillingType().getId()));
                        }
                        if (deliverable.getIntellectualAsset().getPatentStatus() != null
                                && deliverable.getIntellectualAsset().getPatentStatus().getId() != null) {
                            deliverable.getIntellectualAsset()
                                    .setPatentStatus(repIndPatentStatusManager.getRepIndPatentStatusById(
                                            deliverable.getIntellectualAsset().getPatentStatus().getId()));
                        }
                        if (deliverable.getIntellectualAsset().getCountry() != null
                                && deliverable.getIntellectualAsset().getCountry().getId() != null) {
                            deliverable.getIntellectualAsset().setCountry(locElementManager.getLocElementById(
                                    deliverable.getIntellectualAsset().getCountry().getId()));
                        }
                    }
                } else {
                    deliverable.setIntellectualAsset(new DeliverableIntellectualAsset());
                }
            }
            if (deliverable.getDeliverableParticipants() != null) {
                List<DeliverableParticipant> deliverableParticipants = deliverable.getDeliverableParticipants()
                        .stream().filter(c -> c.isActive() && c.getPhase().equals(deliverable.getPhase()))
                        .collect(Collectors.toList());

                if (deliverableParticipants.size() > 0) {
                    deliverable.setDeliverableParticipant(deliverableParticipants.get(0));

                    if (this.transaction != null && !this.transaction.equals("-1")) {
                        if (deliverable.getDeliverableParticipant().getRepIndTypeActivity() != null
                                && deliverable.getDeliverableParticipant().getRepIndTypeActivity()
                                        .getId() != null) {
                            deliverable.getDeliverableParticipant().setRepIndTypeActivity(
                                    repIndTypeActivityManager.getRepIndTypeActivityById(deliverable
                                            .getDeliverableParticipant().getRepIndTypeActivity().getId()));
                        }
                        if (deliverable.getDeliverableParticipant().getRepIndTypeParticipant() != null
                                && deliverable.getDeliverableParticipant().getRepIndTypeParticipant()
                                        .getId() != null) {
                            deliverable.getDeliverableParticipant().setRepIndTypeParticipant(
                                    repIndTypeParticipantManager.getRepIndTypeParticipantById(deliverable
                                            .getDeliverableParticipant().getRepIndTypeParticipant().getId()));
                        }
                        if (deliverable.getDeliverableParticipant().getRepIndGeographicScope() != null
                                && deliverable.getDeliverableParticipant().getRepIndGeographicScope()
                                        .getId() != null) {
                            deliverable.getDeliverableParticipant().setRepIndGeographicScope(
                                    repIndGeographicScopeManager.getRepIndGeographicScopeById(deliverable
                                            .getDeliverableParticipant().getRepIndGeographicScope().getId()));
                        }
                    }
                } else {
                    deliverable.setDeliverableParticipant(new DeliverableParticipant());
                }
            }

            deliverable.setFlagshipValue("");
            deliverable.setRegionsValue("");

            for (DeliverableProgram deliverableProgram : deliverable.getPrograms()) {
                if (deliverable.getFlagshipValue().isEmpty()) {
                    deliverable.setFlagshipValue(deliverableProgram.getCrpProgram().getId().toString());
                } else {
                    deliverable.setFlagshipValue(deliverable.getFlagshipValue() + ","
                            + deliverableProgram.getCrpProgram().getId().toString());
                }
            }

            for (DeliverableProgram deliverableProgram : deliverable.getRegions()) {
                if (deliverable.getRegionsValue().isEmpty()) {
                    deliverable.setRegionsValue(deliverableProgram.getCrpProgram().getId().toString());
                } else {
                    deliverable.setRegionsValue(deliverable.getRegionsValue() + ","
                            + deliverableProgram.getCrpProgram().getId().toString());
                }
            }
            this.setDraft(false);
        }

        if (deliverable.getGenderLevels() != null) {
            for (DeliverableGenderLevel deliverableGenderLevel : deliverable.getGenderLevels()) {
                try {
                    GenderType type = genderTypeManager
                            .getGenderTypeById(deliverableGenderLevel.getGenderLevel());
                    if (type != null) {
                        deliverableGenderLevel.setNameGenderLevel(type.getDescription());
                        deliverableGenderLevel.setDescriptionGenderLevel(type.getCompleteDescription());
                    }
                } catch (Exception e) {
                    LOG.error("unable to update DeliverableGenderLevel", e);
                }
            }
        }

        if (metadataElementManager.findAll() != null) {
            deliverable.setMetadata(new ArrayList<>(metadataElementManager.findAll()));
        }

        genderLevels = new ArrayList<>();
        List<GenderType> genderTypes = null;
        if (this.hasSpecificities(APConstants.CRP_CUSTOM_GENDER)) {
            genderTypes = genderTypeManager.findAll().stream()
                    .filter(c -> c.isActive() && c.getCrp() != null
                            && c.getCrp().getId().longValue() == loggedCrp.getId().longValue())
                    .collect(Collectors.toList());
        } else {
            genderTypes = genderTypeManager.findAll().stream().filter(c -> c.isActive() && c.getCrp() == null)
                    .collect(Collectors.toList());
        }

        for (GenderType projectStatusEnum : genderTypes) {
            genderLevels.add(projectStatusEnum);
        }

        deliverableSubTypes = new ArrayList<>(
                deliverableTypeManager.findAll().stream()
                        .filter(dt -> dt.isActive() && dt.getDeliverableCategory() != null
                                && dt.getDeliverableCategory().getId().intValue() == 49)
                        .collect(Collectors.toList()));
        deliverableSubTypes.add(deliverableTypeManager.getDeliverableTypeById(55));
        deliverableSubTypes.add(deliverableTypeManager.getDeliverableTypeById(56));
        deliverableSubTypes.sort((t1, t2) -> t1.getName().compareTo(t2.getName()));

        crps = new ArrayList<GlobalUnit>();
        for (GlobalUnit crp : crpManager.findAll().stream()
                .filter(c -> c.getId() != this.getLoggedCrp().getId() && c.isActive())
                .collect(Collectors.toList())) {
            crps.add(crp);
        }
        crps.sort((c1, c2) -> c1.getComposedName().compareTo(c2.getComposedName()));

        this.fundingSources = new ArrayList<>();
        this.fundingSources = fundingSourceManager.findAll().stream()
                .filter(fs -> fs.isActive() && fs.getCrp().equals(this.getCurrentCrp())
                        && fs.getFundingSourceInfo(deliverable.getPhase()) != null)
                .collect(Collectors.toList());

        fundingSources.sort((f1, f2) -> f1.getId().compareTo(f2.getId()));

        repositoryChannels = repositoryChannelManager.findAll();
        if (repositoryChannels != null && repositoryChannels.size() > 0) {
            repositoryChannels.sort((rc1, rc2) -> rc1.getShortName().compareTo(rc2.getShortName()));
        } else {
            repositoryChannels = new LinkedList<RepositoryChannel>();
        }

        institutions = new ArrayList<>();
        List<Institution> institutionsList = institutionManager.findAll().stream().filter(c -> c.isActive())
                .collect(Collectors.toList());
        institutionsList.sort((i1, i2) -> i1.getComposedName().compareTo(i2.getComposedName()));
        for (Institution institution : institutionsList) {
            institutions.add(institution);
        }

        // Read all the cross cutting scoring from database
        this.crossCuttingDimensions = this.crossCuttingManager.findAll();

        // load the map of cross cutting scores
        this.crossCuttingScoresMap = new HashMap<>();
        for (CrossCuttingScoring score : this.crossCuttingDimensions) {
            this.crossCuttingScoresMap.put(score.getId(), score.getDescription());
        }

        // only show cross cutting number 1 and 2

        List<CrossCuttingScoring> crossCuttingDimensionsTemp = this.crossCuttingDimensions;
        this.crossCuttingDimensions = new ArrayList<>();

        for (CrossCuttingScoring score : crossCuttingDimensionsTemp) {
            if (score.getId() != 0) {
                this.crossCuttingDimensions.add(score);
            }
        }

        this.setKeyOutputs(crpClusterKeyOutputManager.getCrpClusterKeyOutputByGlobalUnitAndPhase(
                this.loggedCrp.getId(), deliverable.getPhase().getId()));
        this.getKeyOutputs().sort((k1, k2) -> k1.getCrpClusterOfActivity().getIdentifier()
                .compareTo(k2.getCrpClusterOfActivity().getIdentifier()));

        this.setRepIndTypeActivities(repIndTypeActivityManager.findAll().stream()
                .sorted((t1, t2) -> t1.getName().compareTo(t2.getName())).collect(Collectors.toList()));
        this.setRepIndTypeParticipants(repIndTypeParticipantManager.findAll().stream()
                .sorted((t1, t2) -> t1.getName().compareTo(t2.getName())).collect(Collectors.toList()));
        this.setRepIndGeographicScopes(repIndGeographicScopeManager.findAll().stream()
                .sorted((g1, g2) -> g1.getName().compareTo(g2.getName())).collect(Collectors.toList()));
        this.setRepIndRegions(repIndRegionManager.findAll().stream()
                .sorted((r1, r2) -> r1.getName().compareTo(r2.getName())).collect(Collectors.toList()));
        this.setCountries(locElementManager.findAll().stream()
                .filter(c -> c.isActive() && c.getLocElementType().getId() == 2).collect(Collectors.toList()));
        this.setRepIndFillingTypes(repIndFillingTypeManager.findAll().stream()
                .sorted((r1, r2) -> r1.getName().compareTo(r2.getName())).collect(Collectors.toList()));
        this.setRepIndPatentStatuses(repIndPatentStatusManager.findAll().stream()
                .sorted((r1, r2) -> r1.getName().compareTo(r2.getName())).collect(Collectors.toList()));
        // Statuses
        statuses = new HashMap<>();
        List<ProjectStatusEnum> list = Arrays.asList(ProjectStatusEnum.values());
        for (ProjectStatusEnum projectStatusEnum : list) {
            statuses.put(projectStatusEnum.getStatusId(), projectStatusEnum.getStatus());
        }
        // Participants Locations
        if (deliverable.getDeliverableParticipant().getDeliverableParticipantLocations() == null) {
            deliverable.getDeliverableParticipant().setParticipantLocations(new ArrayList<>());
        } else {
            List<DeliverableParticipantLocation> locations = deliverable.getDeliverableParticipant()
                    .getDeliverableParticipantLocations().stream().filter(pl -> pl.isActive())
                    .collect(Collectors.toList());
            deliverable.getDeliverableParticipant().setParticipantLocations(locations);

        }
        if (deliverable.getDeliverableParticipant().getParticipantLocations() != null) {
            for (DeliverableParticipantLocation location : deliverable.getDeliverableParticipant()
                    .getParticipantLocations()) {
                deliverable.getDeliverableParticipant().getParticipantLocationsIsos()
                        .add(location.getLocElement().getIsoAlpha2());
            }
        }

        deliverableDB = deliverableManager.getDeliverableById(deliverable.getId());

        String params[] = { loggedCrp.getAcronym(), deliverable.getId() + "" };
        this.setBasePermission(this.getText(Permission.PUBLICATION_BASE_INSTITUTION, params));

        if (this.isHttpPost()) {

            if (deliverable.getPublication() != null) {
                deliverable.getPublication().setIsiPublication(null);
                deliverable.getPublication().setCoAuthor(null);
                deliverable.getPublication().setNasr(null);
            }

            deliverable.getDeliverableInfo(deliverable.getPhase()).setDeliverableType(null);
            deliverable.getDeliverableInfo(deliverable.getPhase()).setCrossCuttingGender(null);
            deliverable.getDeliverableInfo(deliverable.getPhase()).setCrossCuttingCapacity(null);
            deliverable.getDeliverableInfo(deliverable.getPhase()).setCrossCuttingNa(null);
            deliverable.getDeliverableInfo(deliverable.getPhase()).setCrossCuttingYouth(null);
            deliverable.getDeliverableInfo(deliverable.getPhase()).setIsLocationGlobal(null);
            deliverable.getDeliverableInfo(this.getActualPhase()).setLicense(null);
            deliverable.getDeliverableInfo(this.getActualPhase()).setCrpClusterKeyOutput(null);
            deliverable.setResponsiblePartner(null);

            if (deliverable.getCrps() != null) {
                deliverable.getCrps().clear();
            }
            if (deliverable.getMetadataElements() != null) {
                deliverable.getMetadataElements().clear();
            }

            if (deliverable.getLeaders() != null) {
                deliverable.getLeaders().clear();
            }
            if (deliverable.getPrograms() != null) {
                deliverable.getPrograms().clear();
            }
            deliverable.setFlagshipValue("");
            deliverable.setRegionsValue("");

            if (deliverable.getRegions() != null) {
                deliverable.getRegions().clear();
            }
            if (deliverable.getUsers() != null) {
                deliverable.getUsers().clear();
            }

            if (deliverable.getFundingSources() != null) {
                deliverable.getFundingSources().clear();
            }
            if (deliverable.getGenderLevels() != null) {
                deliverable.getGenderLevels().clear();
            }
            if (deliverable.getDisseminations() != null) {
                deliverable.getDisseminations().clear();
            }
            if (deliverable.getDeliverableParticipant() != null) {
                deliverable.getDeliverableParticipant().setRepIndGeographicScope(null);
                deliverable.getDeliverableParticipant().setRepIndRegion(null);
                deliverable.getDeliverableParticipant().setRepIndTypeActivity(null);
                deliverable.getDeliverableParticipant().setRepIndTypeParticipant(null);
            }
            if (deliverable.getIntellectualAsset() != null) {
                deliverable.getIntellectualAsset().setFillingType(null);
                deliverable.getIntellectualAsset().setPatentStatus(null);
            }
        }
    }
}

From source file:com.diversityarrays.kdxplore.KDXploreFrame.java

private void initialiseKdxApps() throws IOException {

    String[] classNames = KdxploreConfig.getInstance().getMainPluginClassNames();
    if (classNames != null && classNames.length > 0) {
        List<String> classNamesToLoad = new ArrayList<>();
        Collections.addAll(classNamesToLoad, classNames);
        if (!classNamesToLoad.contains(OFFLINE_DATA_APP_SERVICE_CLASS_NAME)) {
            classNamesToLoad.add(0, OFFLINE_DATA_APP_SERVICE_CLASS_NAME);
            classNames = classNamesToLoad.toArray(new String[classNamesToLoad.size()]);
        }/*from   w  w w  .  j  a v  a  2s . c o  m*/
    }

    Map<KdxApp, Component> componentByApp = collectKdxApps(classNames);

    appByComponent.clear();
    for (KdxApp app : componentByApp.keySet()) {
        Component comp = componentByApp.get(app);
        if (comp != null) {
            appByComponent.put(comp, app);
        }
    }

    allKdxApps.clear();
    allKdxApps.addAll(componentByApp.keySet());

    // Initialise the apps in initialisation order.
    allKdxApps.sort(Comparator.comparing(KdxApp::getInitialisationOrder));

    // And while we're initialising them we collect
    // those that can perform a databaseBackup (i.e. have a BackupProvider).
    backupProviders.clear();
    List<KdxApp> wantedAppsWithUi = new ArrayList<>();

    for (KdxApp app : allKdxApps) {
        BackupProvider bp = app.getBackupProvider();
        if (bp != null) {
            backupProviders.add(bp);
        }

        /**
         * See {@link com.diversityarrays.kdxplore.prefs.KdxplorePreferences#SHOW_ALL_APPS}
         */
        if (appIsWanted(app)) {
            try {
                app.initialiseAppBeforeUpdateCheck(appInitContext);
            } catch (Exception e) {
                String msg = Msg.MSG_KDXAPP_INIT_PROBLEM(app.getAppName());
                Shared.Log.w(TAG, msg, e);
                messagesPanel.println(msg);
                messagesPanel.println(e.getMessage());
            }
        }

        if (appIsWanted(app) && null != componentByApp.get(app)) {
            wantedAppsWithUi.add(app);
        }
    }

    // - - - - - - - - - - - - - - - - - - - - -
    // Display the apps in display order.
    wantedAppsWithUi.sort(Comparator.comparing(KdxApp::getDisplayOrder));
    backupProviders.sort(Comparator.comparing(BackupProvider::getDisplayOrder));

    switch (wantedAppsWithUi.size()) {
    case 0:
        JLabel label = new JLabel(Msg.MSG_NO_KDXPLORE_APPS_AVAILABLE());
        label.setHorizontalAlignment(JLabel.CENTER);
        cardPanel.add(label, CARD_KDXAPPS);
        break;
    case 1:
        KdxApp kdxApp = wantedAppsWithUi.get(0);
        Component uiComponent = componentByApp.get(kdxApp);

        Component appComponent = makeComponentForTab(kdxApp, uiComponent);
        cardPanel.add(appComponent, CARD_KDXAPPS);

        getRootPane().setDefaultButton(kdxApp.getDefaultButton());

        String msg = Msg.MSG_SHOWING_KDXAPP(kdxApp.getAppName());
        messagesPanel.println(msg);
        System.err.println(msg + " uiClass=" //$NON-NLS-1$
                + uiComponent.getClass().getName());
        break;
    default:
        kdxAppTabs = new JTabbedPane(JTabbedPane.LEFT);
        cardPanel.add(kdxAppTabs, CARD_KDXAPPS);
        Bag<String> tabsSeen = new HashBag<>();
        for (KdxApp app : wantedAppsWithUi) {
            Component ui = componentByApp.get(app);

            String tabName = app.getAppName();
            DevelopmentState devState = app.getDevelopmentState();
            switch (devState) {
            case ALPHA:
                tabName = tabName + " (\u03b1)"; // TODO move to UnicodeChars
                break;
            case BETA:
                tabName = tabName + " (\u03b2)"; // TODO move to UnicodeChars
                break;
            case PRODUCTION:
                break;
            default:
                tabName = tabName + " " + devState.name();
                break;
            }
            tabsSeen.add(tabName);
            int count = tabsSeen.getCount(tabName);
            if (count > 1) {
                tabName = tabName + "_" + count; //$NON-NLS-1$
            }

            Component tabComponent = makeComponentForTab(app, ui);
            kdxAppTabs.addTab(tabName, tabComponent);
            if (macapp == null) {
                int index = kdxAppTabs.indexOfTab(tabName);
                if (index >= 0) {
                    JLabel tabLabel = new JLabel(tabName);
                    tabLabel.setBorder(new EmptyBorder(2, 2, 2, 2));
                    tabLabel.setUI(new VerticalLabelUI(VerticalLabelUI.UPWARDS));
                    kdxAppTabs.setTabComponentAt(index, tabLabel);
                }
            }
            messagesPanel.println(Msg.MSG_SHOWING_KDXAPP(tabName));
        }

        kdxAppTabs.addChangeListener(kdxAppTabsChangeListener);
        kdxAppTabs.setSelectedIndex(0);
        break;
    }
}

From source file:org.structr.web.maintenance.DeployCommand.java

private void exportMailTemplates(final Path target) throws FrameworkException {

    logger.info("Exporting mail templates");

    final PropertyKey<String> textKey = StructrApp.key(MailTemplate.class, "text");
    final PropertyKey<String> localeKey = StructrApp.key(MailTemplate.class, "locale");
    final List<Map<String, Object>> mailTemplates = new LinkedList<>();
    final App app = StructrApp.getInstance();

    try (final Tx tx = app.tx()) {

        for (final MailTemplate mailTemplate : app.nodeQuery(MailTemplate.class).sort(MailTemplate.name)
                .getAsList()) {/*from  w  w  w  .j  av  a  2s  .c  o  m*/

            final Map<String, Object> entry = new TreeMap<>();
            mailTemplates.add(entry);

            entry.put("name", mailTemplate.getProperty(MailTemplate.name));
            entry.put("text", mailTemplate.getProperty(textKey));
            entry.put("locale", mailTemplate.getProperty(localeKey));
            entry.put("visibleToAuthenticatedUsers",
                    mailTemplate.getProperty(MailTemplate.visibleToAuthenticatedUsers));
            entry.put("visibleToPublicUsers", mailTemplate.getProperty(MailTemplate.visibleToPublicUsers));
        }

        tx.success();
    }

    try (final Writer fos = new OutputStreamWriter(new FileOutputStream(target.toFile()))) {

        mailTemplates.sort(new AbstractMapComparator<Object>() {
            @Override
            public String getKey(Map<String, Object> map) {
                return ((String) map.get("name")).concat(((String) map.get("locale")));
            }
        });

        getGson().toJson(mailTemplates, fos);

    } catch (IOException ioex) {
        logger.warn("", ioex);
    }
}

From source file:org.optaplanner.examples.conferencescheduling.persistence.ConferenceSchedulingCfpDevoxxImporter.java

private void importSpeakerList() {
    this.speakerNameToSpeakerMap = new HashMap<>();
    this.talkUrlSet = new HashSet<>();
    List<Speaker> speakerList = new ArrayList<>();

    String speakersUrl = conferenceBaseUrl + "/speakers";
    LOGGER.debug("Sending a request to: " + speakersUrl);
    JsonArray speakerArray = readJson(speakersUrl, JsonReader::readArray);

    for (int i = 0; i < speakerArray.size(); i++) {
        String speakerUrl = speakerArray.getJsonObject(i).getJsonArray("links").getJsonObject(0)
                .getString("href");
        LOGGER.debug("Sending a request to: " + speakerUrl);
        JsonObject speakerObject = readJson(speakerUrl, JsonReader::readObject);

        String speakerId = speakerObject.getString("uuid");
        String speakerName = speakerObject.getString("firstName") + " " + speakerObject.getString("lastName");

        if (Arrays.asList(IGNORED_SPEAKER_NAMES).contains(speakerName)) {
            continue;
        }/* w w w  .j  a v  a  2  s.co  m*/
        Speaker speaker = new Speaker((long) i);
        speaker.setName(speakerName);
        speaker.withPreferredRoomTagSet(new HashSet<>()).withPreferredTimeslotTagSet(new HashSet<>())
                .withProhibitedRoomTagSet(new HashSet<>()).withProhibitedTimeslotTagSet(new HashSet<>())
                .withRequiredRoomTagSet(new HashSet<>()).withRequiredTimeslotTagSet(new HashSet<>())
                .withUnavailableTimeslotSet(new HashSet<>()).withUndesiredRoomTagSet(new HashSet<>())
                .withUndesiredTimeslotTagSet(new HashSet<>());
        speakerList.add(speaker);
        if (speakerNameToSpeakerMap.keySet().contains(speakerName)) {
            throw new IllegalStateException("Speaker (" + speakerName + ") with id (" + speakerId
                    + ") already exists in the speaker list");
        }
        speakerNameToSpeakerMap.put(speakerName, speaker);

        JsonArray speakerTalksArray = speakerObject.getJsonArray("acceptedTalks");
        for (int j = 0; j < speakerTalksArray.size(); j++) {
            String talkUrl = speakerTalksArray.getJsonObject(j).getJsonArray("links").getJsonObject(0)
                    .getString("href");
            talkUrlSet.add(talkUrl);
        }
    }

    speakerList.sort(Comparator.comparing(Speaker::getName));
    solution.setSpeakerList(speakerList);
}

From source file:org.wso2.security.tools.advisorytool.builders.CustomerSecurityAdvisoryBuilder.java

@Override
public void buildAdvisory() throws AdvisoryToolException {
    List<String> affectedPatchNames = new ArrayList<>();
    List<Patch> supportedPatchListForAdvisory = new ArrayList<>();

    //creating the list of patch supported products.
    List<Product> affectedPatchSupportedProducts = getPatchSupportedProducts(
            securityAdvisory.getAffectedAllProducts());
    securityAdvisory.setAffectedPatchProducts(affectedPatchSupportedProducts);

    //generate the patch details file to be used to upload the patches to the customer patch locations.
    generatePatchUploadDataFile(securityAdvisory.getName(), affectedPatchSupportedProducts);

    //creating the list of WUM supported products.
    List<Product> affectedWUMProductsList = getWUMProductsFromAffectedProducts(
            securityAdvisory.getAffectedAllProducts());
    securityAdvisory.setAffectedWUMProducts(affectedWUMProductsList);

    //creating the patch list with the customer patch download link.
    for (Product affectedPatchSupportedProduct : affectedPatchSupportedProducts) {
        for (Version affectedPatchSupportedVersion : affectedPatchSupportedProduct.getVersionList()) {
            for (String patchName : affectedPatchSupportedVersion.getPatchNamesList()) {

                for (Platform platform : Configuration.getInstance().getPlatforms()) {

                    if (affectedPatchSupportedVersion.getPlatformVersionNumber()
                            .equals(platform.getVersionNumber())) {

                        Patch patch = new Patch();
                        patch.setName(patchName);

                        //building the customer patch download URL.
                        String url = Configuration.getInstance().getPatchZIPCustomerLocation()
                                + platform.getPatchDirectoryName() + "/Product/"
                                + affectedPatchSupportedProduct.getCodeName() + " "
                                + affectedPatchSupportedVersion.getVersionNumber() + "/"
                                + patchName.replace(" ", "") + ".zip";

                        patch.setZipLocation(url);

                        if (!affectedPatchNames.contains(patchName)) {
                            affectedPatchNames.add(patchName);
                            supportedPatchListForAdvisory.add(patch);
                        }//  w  w  w.  j a  v a  2s .co  m
                    }
                }
            }
        }

    }
    supportedPatchListForAdvisory.sort(Comparator.comparing(Patch::getName));
    securityAdvisory.setApplicablePatchList(supportedPatchListForAdvisory);
}

From source file:org.structr.web.maintenance.DeployCommand.java

private void exportLocalizations(final Path target) throws FrameworkException {

    logger.info("Exporting localizations");

    final PropertyKey<String> localizedNameKey = StructrApp.key(Localization.class, "localizedName");
    final PropertyKey<String> domainKey = StructrApp.key(Localization.class, "domain");
    final PropertyKey<String> localeKey = StructrApp.key(Localization.class, "locale");
    final PropertyKey<String> importedKey = StructrApp.key(Localization.class, "imported");
    final List<Map<String, Object>> localizations = new LinkedList<>();
    final App app = StructrApp.getInstance();

    try (final Tx tx = app.tx()) {

        for (final Localization localization : app.nodeQuery(Localization.class).sort(Localization.name)
                .getAsList()) {//from w  w  w  . ja va2  s .  co m

            final Map<String, Object> entry = new TreeMap<>();
            localizations.add(entry);

            entry.put("name", localization.getProperty(Localization.name));
            entry.put("localizedName", localization.getProperty(localizedNameKey));
            entry.put("domain", localization.getProperty(domainKey));
            entry.put("locale", localization.getProperty(localeKey));
            entry.put("imported", localization.getProperty(importedKey));
            entry.put("visibleToAuthenticatedUsers",
                    localization.getProperty(MailTemplate.visibleToAuthenticatedUsers));
            entry.put("visibleToPublicUsers", localization.getProperty(MailTemplate.visibleToPublicUsers));
        }

        tx.success();
    }

    try (final Writer fos = new OutputStreamWriter(new FileOutputStream(target.toFile()))) {

        localizations.sort(new AbstractMapComparator<Object>() {
            @Override
            public String getKey(Map<String, Object> map) {

                final Object name = map.get("name");
                final Object domain = map.get("domain");
                final Object locale = map.get("locale");

                // null domain is replaced by a string so that those localizations are shown first
                return (name != null ? name.toString() : "null")
                        .concat((domain != null ? domain.toString() : "00-nulldomain"))
                        .concat((locale != null ? locale.toString() : "null"));
            }
        });

        final Gson gson = new GsonBuilder().serializeNulls().create();

        final StringBuilder sb = new StringBuilder("[");

        List<String> jsonStrings = new LinkedList();

        for (Map<String, Object> loc : localizations) {
            jsonStrings.add("\t" + gson.toJson(loc));
        }

        if (!jsonStrings.isEmpty()) {

            sb.append("\n").append(String.join(",\n", jsonStrings)).append("\n");

        }

        sb.append("]");

        fos.write(sb.toString());

        //         getGson().toJson(localizations, fos);

    } catch (IOException ioex) {
        logger.warn("", ioex);
    }
}

From source file:com.evolveum.midpoint.model.impl.lens.TestAssignmentProcessor2.java

private String getStringRepresentation(EvaluationOrder order) {
    List<String> names = new ArrayList<>();
    for (@NotNull
    QName relation : order.getRelations()) {
        int count = order.getMatchingRelationOrder(relation);
        if (count == 0) {
            continue;
        } else if (count < 0) {
            fail("Negative count for " + relation + " in " + order);
        }// www.  j  a v  a2 s.  c  o m
        while (count-- > 0) {
            names.add(relation.getLocalPart());
        }
    }
    names.sort(String::compareTo);
    return StringUtils.join(names, " ");
}