Example usage for java.util Collection removeAll

List of usage examples for java.util Collection removeAll

Introduction

In this page you can find the example usage for java.util Collection removeAll.

Prototype

boolean removeAll(Collection<?> c);

Source Link

Document

Removes all of this collection's elements that are also contained in the specified collection (optional operation).

Usage

From source file:org.apache.click.extras.tree.CheckboxTree.java

/**
 * Binds the users request of selected nodes to the tree's nodes.
 * <p/>// www .  j  ava2  s.  c  om
 * This method is automatically invoked when the CheckboxTree's parent form
 * is submitted.
 * <p/>
 * See {@link #onFormSubmission()} for more details.
 * <p/>
 * If you do not want CheckboxTree to automatically invoke this method,
 * you can override {@link #onFormSubmission()} to do nothing by default.
 * <p/>
 * Then you must manually invoke this method when the form is submitted.
 * For example:
 *
 * <pre class="prettyprint">
 * public void onInit() {
 *     CheckboxTree tree = new CheckboxTree("tree") {
 *         public void onFormSubmission() {
 *             // Do nothing
 *         }
 *     }
 *     Form form = createForm();
 *     form.add(tree);
 *     Submit submit = new Submit("save");
 *     form.add(submit);
 *     submit.setActionListener(new ActionListener() {
 *         public boolean onAction(Control source) {
 *             tree.bindSelectOrDeselectValues();
 *             return true;
 *         }
 *     });
 *     addControl(form);
 * } </pre>
 */
@Override
public void bindSelectOrDeselectValues() {
    // With html forms, only "checked" checkbox values are submitted
    // to the server. So the request does not supply us the information
    // needed to calculate the nodes to be deselected. To find the nodes to
    // deselect, the newly selected nodes are subtracted from the currently
    // selected nodes. This implies that the tree's model is stored between
    // http requests.

    // To find the collection of selected nodes, the HttpServletRequest is
    // checked against the value of the field {@link #SELECT_TREE_NODE_PARAM}.

    // find id's of all the new selected node's'
    String[] nodeIds = getRequestValues(SELECT_TREE_NODE_PARAM);

    // find currently selected nodes
    boolean includeInvisibleNodes = isSelectChildNodes();
    Collection<TreeNode> currentlySelected = getSelectedNodes(includeInvisibleNodes);

    // is there any new selected node's
    if (nodeIds == null || nodeIds.length == 0) {
        // deselect all the current selected nodes
        setSelectState(currentlySelected, false);
        return;
    }
    // build hashes of id's for fast lookup
    Set<String> hashes = new HashSet<String>();
    List<TreeNode> newSelectedNodes = new ArrayList<TreeNode>();
    for (int i = 0; i < nodeIds.length; i++) {
        hashes.add(nodeIds[i]);
    }
    nodeIds = null;

    // build list of newSelectedNodes
    for (Iterator<TreeNode> it = iterator(getRootNode()); it.hasNext();) {
        TreeNode result = it.next();
        if (hashes.contains(result.getId())) {
            newSelectedNodes.add(result);
        }
    }

    // calculate nodes for deselection by removing from currentlySelected nodes
    // those that must be selected.
    currentlySelected.removeAll(newSelectedNodes);

    setSelectState(currentlySelected, false);
    setSelectState(newSelectedNodes, true);
}

From source file:it.iit.genomics.cru.igb.bundles.mi.business.MIWorker.java

@Override
public ArrayList<MIResult> doInBackground() {

    // Display the log tab
    MIView.getInstance().getResultsTabbedPan().setSelectedIndex(0);

    UniprotkbUtils uniprotUtil = UniprotkbUtils.getInstance(query.getTaxid());

    // Create a new Symmetry manager for each query
    symManager = new MISymManager(this.trackId);

    Collection<SeqSymmetry> selectedSyms = query.getSelectedSymmetries();

    // Initialize progress property.
    progressBar.setIndeterminate(false);
    ProgressManager progressManager = new ProgressManager(5);

    setProgress(progressManager.getProgress());

    Set<String> queryUniprotAcs = new HashSet<>();
    Set<String> targetUniprotAcs = new HashSet<>();

    // interactions
    MapOfMap<String, String> uniprotAc2uniprotAcs;

    // Interaction found
    ArrayList<MIResult> resultsInBackground = new ArrayList<>();

    logAndPublish("map selection to genome and proteins..");

    // Step 1//from www . j av a2s .c  om
    progressManager.nextMajorStep(selectedSyms.size());
    // Get gene Symmetries covered by query symmetries
    // don't create container at the moment: many genes syms for a single
    // gene may be present

    // Order list of syms
    SymListOrderer list = new SymListOrderer();

    for (SeqSymmetry querySym : selectedSyms) {
        list.addSymmetry(querySym);
    }

    for (BioSeq chr : list.getSequences()) {
        ArrayList<SeqSymmetry> querySyms = list.getSymmetries(chr);
        getGenes(querySyms, chr, true);
        // for (MIGene gene : getGenes(querySyms, chr, true)) {
        // // load exons (we only need this for the selected ones)
        // miGene2selectedSyms.add(gene, querySym);
        // }
        progressManager.nextStep();
        setProgress(progressManager.getProgress());
    }

    // Step 2
    progressManager.nextMajorStep(miGene2selectedSyms.keySet().size());
    // Associate selected residues
    for (MIGene gene : miGene2selectedSyms.keySet()) {

        logAndPublish("Associate residues to " + gene.getID());

        MoleculeEntry protein = gene.getProtein();

        if (protein != null) {
            queryUniprotAcs.add(protein.getUniprotAc());

            MISymContainer container = symManager.getByProtein(protein);
            symManager.addGeneSymmetry(container, gene);

            symManager.addSelectedSymmetry(container, gene);
        } else {
            igbLogger.getLogger().warn("No protein for {0}", gene.getID());
        }
        progressManager.nextStep();
        setProgress(progressManager.getProgress());
    }

    // Step 3
    progressManager.nextMajorStep(queryUniprotAcs.size());

    // Get interactors
    uniprotAc2uniprotAcs = new MapOfMap<>(queryUniprotAcs);

    logAndPublish("get interactions");

    HashMap<String, MoleculeEntry> targetUniprotEntries = new HashMap<>();

    InteractionManager interactors = new InteractionManager();

    for (String ac : queryUniprotAcs) {

        logAndPublish("Get interactions for " + ac);

        if (ac == null) {
            continue;
        }

        try {
            if (false == PsicquicInitWorker.nullServer.equals(query.getPsiquicServer())
                    && null != query.getPsiquicServer()) {
                for (Interaction interaction : PsicquicUtils.getInstance()
                        .getInteractors(query.getPsiquicServer(), ac)) {
                    interactors.merge(interaction);
                }
            }
        } catch (BridgesRemoteAccessException be) {
            igbLogger.severe("Cannot access PSICQUIC server!");
            break;
        }

        //         // Add interactors from User structures?
        //         if (null != query.getUserStructuresPath() && query.searchUserStructures()) {
        //            Interactome3DLocalRepository userStructures = UserStructuresManager.getInstance()
        //                  .getUserRepository(query.getUserStructuresPath());
        //            for (String interactorAc : userStructures.getInteractors(ac)) {
        //               interactors.getOrCreateInteraction(ac, interactorAc).addType(INTERACTION_TYPE_I3D);
        //               uniprotNeedMapping.add(interactorAc);
        //            }
        //         }

        // Add interactors from I3D?
        if (query.searchInteractome3D() || query.searchDSysMap()) {
            // Check or download I3D interaction file

            // get it from local repository?
            Interactome3DLocalRepository userStructures;
            //            System.out.println("I3D cache: " +  MIBundleConfiguration.getInstance().getI3DStructuresDirectory());
            if (null != MIBundleConfiguration.getInstance().getI3DStructuresDirectory()) {
                userStructures = UserStructuresManager.getInstance()
                        .getUserRepository(MIBundleConfiguration.getInstance().getI3DStructuresDirectory());
            } else {
                I3DDownload download = new I3DDownload(MIBundleConfiguration.getInstance().getCachePath());

                if (false == download.isDatDownloaded(query.getTaxid())) {
                    logAndPublish("download interactions from Interactome3D");
                    download.downloadDat(query.getTaxid());
                }

                // get interactions
                userStructures = UserStructuresManager.getInstance()
                        .getUserRepository(download.getI3DdatPath(query.getTaxid()));
            }

            for (String interactorAc : userStructures.getInteractors(ac)) {
                interactors.getOrCreateInteraction(ac, interactorAc)
                        .addType("direct interaction (Interactome3D)");
                uniprotNeedMapping.add(interactorAc);
            }
        }

        // add interactors from PDB structures
        if (query.searchPDB() || query.searchPDBLocal() || query.searchEPPIC()) {
            MoleculeEntry entry = symManager.getByProteinAc(ac).getEntry();

            PDBWSClient client = new PDBWSClient();
            // Do only 10 by 10
            List<String> pdbs = new ArrayList<>();
            pdbs.addAll(entry.getPdbs());

            while (false == pdbs.isEmpty()) {
                List<String> subset = pdbs.subList(0, Math.min(10, pdbs.size()));
                pdbs = pdbs.subList(Math.min(10, pdbs.size()), pdbs.size());

                if (query.searchPPI() || query.searchNucleicAcid()) {

                    MoleculeDescription molDesc;
                    try {
                        molDesc = client.getDescription(subset);
                    } catch (BridgesRemoteAccessException be) {
                        igbLogger.severe("Cannot access PDB!");
                        break;
                    }

                    if (molDesc != null) {
                        for (StructureID structureId : molDesc.getStructureId()) {

                            for (Polymer polymer : structureId.getPolymers()) {
                                if (polymer.getPolymerDescription() == null) {
                                    igbLogger.severe("No description for " + structureId.getId());
                                }
                                if (null != polymer.getType()) {
                                    switch (polymer.getType()) {
                                    case "protein":
                                        if (query.searchPPI() && null != polymer.getMacromolecule()) {
                                            String proteinAc = polymer.getMacromolecule().getAccession().get(0);

                                            if (false == proteinAc.equals(entry.getUniprotAc())
                                                    || polymer.getChains().size() > 1) {

                                                interactors.getOrCreateInteraction(ac, proteinAc)
                                                        .addType(INTERACTION_TYPE_PDB);
                                                uniprotNeedMapping.add(ac);
                                            }
                                        }
                                        break;
                                    case "dna":
                                        if (false == query.searchNucleicAcid()) {
                                            break;
                                        }
                                        // Merge all DNA entries, use "DNA
                                        // as name rather that the
                                        // desciption
                                        MISymContainer dnaSym = symManager
                                                .getByProteinAc(MoleculeEntry.TAXID_DNA);
                                        uniprotNeedMapping.add(ac);

                                        interactors.getOrCreateInteraction(ac, MoleculeEntry.TAXID_DNA)
                                                .addType(INTERACTION_TYPE_PDB);

                                        if (dnaSym == null) {
                                            MoleculeEntry dnaEntry = new MoleculeEntry(MoleculeEntry.TAXID_DNA);
                                            dnaEntry.setSequence("");
                                            dnaEntry.setTaxid(MoleculeEntry.TAXID_DNA);

                                            targetUniprotEntries.put(MoleculeEntry.TAXID_DNA, dnaEntry);
                                            dnaEntry.addGeneName(MoleculeEntry.TAXID_DNA);

                                            dnaSym = symManager.getByProtein(dnaEntry);
                                        }

                                        MoleculeEntry dnaEntry = dnaSym.getEntry();

                                        for (Chain chain : polymer.getChains()) {
                                            ChainMapping chainMapping = new ChainMapping(structureId.getId(),
                                                    chain.getId(), 0, 0);
                                            dnaEntry.addChain(structureId.getId(), chainMapping, "unspecified");
                                        }

                                        break;

                                    case "rna":
                                        if (false == query.searchNucleicAcid()) {
                                            break;
                                        }
                                        uniprotNeedMapping.add(ac);
                                        // Merge all RNA entries, use "RNA
                                        // as name rather that the
                                        // desciption
                                        MISymContainer rnaSym = symManager
                                                .getByProteinAc(MoleculeEntry.TAXID_RNA);

                                        interactors.getOrCreateInteraction(ac, MoleculeEntry.TAXID_RNA)
                                                .addType(INTERACTION_TYPE_PDB);

                                        if (rnaSym == null) {
                                            MoleculeEntry rnaEntry = new MoleculeEntry(MoleculeEntry.TAXID_RNA);
                                            rnaEntry.setSequence("");
                                            rnaEntry.setTaxid(MoleculeEntry.TAXID_RNA);

                                            targetUniprotEntries.put(MoleculeEntry.TAXID_RNA, rnaEntry);
                                            rnaEntry.addGeneName(MoleculeEntry.TAXID_RNA);

                                            rnaSym = symManager.getByProtein(rnaEntry);
                                        }

                                        MoleculeEntry rnaEntry = rnaSym.getEntry();

                                        for (Chain chain : polymer.getChains()) {
                                            ChainMapping chainMapping = new ChainMapping(structureId.getId(),
                                                    chain.getId(), 0, 0);
                                            rnaEntry.addChain(structureId.getId(), chainMapping, "unspecified");
                                        }

                                        break;
                                    }
                                }
                            }
                        }
                    }
                }
                if (query.searchLigands() && false == query.searchEPPIC()) {
                    try {
                        for (Ligand ligand : client.getLigands(subset)) {

                            /**
                             * Only non polymer ligands
                             */
                            if (false == ligand.isNonPolymer()) {
                                continue;
                            }

                            int numAtoms = 0;

                            for (String atom : ligand.getFormula().split(" ")) {

                                String num = atom.replaceAll("\\D+", "").trim();
                                if ("".equals(num)) {
                                    numAtoms++;
                                } else {
                                    numAtoms += Integer.parseInt(num);
                                }
                            }

                            if (numAtoms <= 10) {
                                igbLogger.info("Skip ligand: " + ligand.getFormula());
                                continue;
                            }
                            uniprotNeedMapping.add(ac);
                            MISymContainer misym = symManager.getByProteinAc(ligand.getChemicalName());

                            interactors.getOrCreateInteraction(ac, ligand.getChemicalName())
                                    .addType(INTERACTION_TYPE_PDB);

                            if (misym == null) {
                                MoleculeEntry ligandEntry = new MoleculeEntry(ligand.getChemicalName());
                                ligandEntry.setSequence("");
                                ligandEntry.setTaxid(MoleculeEntry.TAXID_LIGAND);

                                ligandEntry.addGeneName(ligand.getChemicalId());
                                targetUniprotEntries.put(ligand.getChemicalName(), ligandEntry);

                                misym = symManager.getByProtein(ligandEntry);
                            }

                            MoleculeEntry ligandEntry = misym.getEntry();

                            ChainMapping chainMapping = new ChainMapping(ligand.getStructureId(), "ligand", 0,
                                    0);
                            ligandEntry.addChain(ligand.getStructureId(), chainMapping, "unspecified");

                        }
                    } catch (BridgesRemoteAccessException be) {
                        igbLogger.severe("Cannot access PDB!");
                        break;
                    }
                }
            }

        }

        if (query.searchModifications()) {
            MoleculeEntry entry = symManager.getByProteinAc(ac).getEntry();

            for (ModifiedResidue modification : entry.getModifications()) {
                MISymContainer misym = symManager.getByProteinAc(modification.getDescription());

                uniprotNeedMapping.add(ac);
                if (misym == null) {

                    interactors.getOrCreateInteraction(ac, modification.getDescription())
                            .addType("direct interaction (Uniprot)");
                    // interactors.add(modification.getDescription(),
                    // "association");
                    MoleculeEntry ligandEntry = new MoleculeEntry(modification.getDescription());
                    ligandEntry.setSequence("");
                    ligandEntry.setTaxid(MoleculeEntry.TAXID_MODIFICATION);

                    ligandEntry.addGeneName(modification.getDescription());
                    targetUniprotEntries.put(modification.getDescription(), ligandEntry);

                    symManager.getByProtein(ligandEntry);
                }

            }

        }

        Collection<String> interactorUniprotAcs = interactors.getInteractors();

        for (String interactorUniprotAc : interactorUniprotAcs) {
            // Skip interaction if we the type of query is INTRA (i.e. only
            // interactions between selected genes)
            // and one of the protein was not selected
            if (QueryType.EXTRA.equals(query.getQueryType()) || queryUniprotAcs.contains(interactorUniprotAc)) {
                uniprotAc2uniprotAcs.add(ac, interactorUniprotAc);
                targetUniprotAcs.add(interactorUniprotAc);

                // String key = ac + "#" + interactorUniprotAc;
                // interactionTypes.addAll(key,
                // interactors.get(interactorUniprotAc));
                // At this point we may not have created the symmetry
            }
        }

        progressManager.nextStep();
        setProgress(progressManager.getProgress());
    }

    // Only look for uniprot Acs for which we don't have an entry yet
    HashSet<String> uniprotAcToSearch = new HashSet<>();

    uniprotAcToSearch.addAll(targetUniprotAcs);

    uniprotAcToSearch.removeAll(symManager.getProteinAcs());

    // Allow proteins from other species
    try {
        targetUniprotEntries
                .putAll(uniprotUtil.getUniprotEntriesFromUniprotAccessions(uniprotAcToSearch, false));
    } catch (BridgesRemoteAccessException be) {
        igbLogger.severe("Cannot access Uniprot!");

        return resultsInBackground;
    }

    for (MoleculeEntry entry : targetUniprotEntries.values()) {
        MISymContainer container = symManager.getByProtein(entry);
        if (container == null) {
        }
    }

    // missing ones?
    Collection<String> missingUniprotAcs = new ArrayList<>();

    missingUniprotAcs.addAll(uniprotAcToSearch);

    missingUniprotAcs.removeAll(targetUniprotEntries.keySet());

    for (String missingAc : missingUniprotAcs) {
        MICommons.getInstance().addProteinToBlackList(missingAc);
    }

    for (MISymContainer container : symManager.getQueryContainers()) {
        if (null != container.getEntry()) {
            targetUniprotEntries.put(container.getEntry().getUniprotAc(), container.getEntry());
        }
    }

    // Do I need it if I don't need symmetries?
    // Step 4
    progressManager.nextMajorStep(targetUniprotEntries.values().size());
    for (MoleculeEntry uniprotEntry : targetUniprotEntries.values()) {

        logAndPublish("create symmetry for " + uniprotEntry.getUniprotAc());

        // Get symmetry, it has not been necessarily created
        MISymContainer container = symManager.getByProtein(uniprotEntry);

        Collection<String> geneIds;

        // Check if we are using Ensembl web service or QuickLoad.
        if (EnsemblGeneManager.class.isInstance(geneManager)) {
            geneIds = uniprotEntry.getEnsemblGenes();
        } else {
            geneIds = new HashSet<>();
            geneIds.addAll(uniprotEntry.getGeneNames());
            geneIds.addAll(uniprotEntry.getRefseqs());
            geneIds.addAll(uniprotEntry.getEnsemblGenes());
        }

        SimpleSymWithProps overlappingSym = new SimpleSymWithProps();
        overlappingSym.setProperty(TrackLineParser.ITEM_RGB, Color.RED);

        overlappingSym.setID(this.trackId + "-" + uniprotEntry.getGeneName());

        for (String geneId : geneIds) {

            Collection<MIGene> genes = geneManager.getByID(geneId);

            // For each gene create a "result symmetry", which will be
            // displayed in the interaction track
            if (genes.isEmpty()) {
                continue;
            }

            RangeMerger merger = new RangeMerger();

            for (MIGene gene : genes) {

                if (null == gene) {
                    continue;
                }

                if (null != uniprotEntry.getVarSpliceAC(gene.getID())) {

                    gene.getUniprotAcs().add(uniprotEntry.getUniprotAc());
                    gene.setProtein(uniprotEntry);
                    symManager.addGeneSymmetry(container, gene);

                    BioSeq chromosome = geneManager.getSequence(gene.getChromosomeName());

                    if (chromosome == null) {
                        igbLogger.severe("Unavailable sequence: " + gene.getChromosomeName()
                                + ", there may be a network problem.");
                        continue;
                    }

                    merger.addRange(chromosome.getId(), new Range(gene.getMin(), gene.getMax()));
                }
            }

            for (String seq : merger.getSequences()) {
                BioSeq chromosome = geneManager.getSequence(seq);

                if (chromosome == null) {
                    igbLogger.severe("No sequence for chromosome: " + seq);
                }
                for (Range range : merger.getRanges(seq)) {
                    SeqSpan span = new SimpleSeqSpan(range.getMin(), range.getMax(), chromosome);

                    // Check if it has already this span
                    boolean hasSpan = false;
                    for (int i = 0; i < overlappingSym.getSpanCount(); i++) {
                        SeqSpan otherSpan = overlappingSym.getSpan(i);
                        if (otherSpan.getMin() == span.getMin() && otherSpan.getMax() == span.getMax()) {
                            hasSpan = true;
                            break;
                        }
                    }

                    if (false == hasSpan) {
                        overlappingSym.addSpan(span);
                    }
                }
            }

            if (false == genes.isEmpty()) {
                // we found it
                break;
            }
        }

        symManager.setResultSym(container, overlappingSym);

        progressManager.nextStep();
        setProgress(progressManager.getProgress());

    }

    for (String ac : uniprotNeedMapping) {
        MISymContainer proteinContainer = symManager.getByProteinAc(ac);
        for (MIGene gene : proteinContainer.getMiGenes()) {

            if (false == miGene2selectedSyms.containsKey(gene)) {
                continue;
            }
            for (SeqSymmetry selectedSym : miGene2selectedSyms.get(gene)) {
                logAndPublish("Load residues for " + gene.getID());
                geneManager.loadTranscriptSequence(selectedSym.getSpanSeq(0), gene);

                // Maybe the protein was already assigned to the gene.
                // In order to be sure we are working on the right one,
                // Don't use the protein variable, but get it fromthe gene
                ArrayList<AAPosition> aaPositions = new ArrayList<>();

                // symmetry are 0-based exclusive,
                // use max -1 to have inclusive coordinates
                Collection<AAPosition> positions = AAPositionManager.getAAPositionManager(query.getLabel())
                        .getAAPositions(gene, selectedSym.getSpan(0).getMin(),
                                selectedSym.getSpan(0).getMax() - 1);
                aaPositions.addAll(positions);

                for (AAPosition aa : aaPositions) {
                    gene2pos.add(gene, aa);
                }
                symManager.addSelectedResidues(gene.getProtein(), aaPositions);
            }
        }
    }

    // Step 5
    // don't add twice the same interaction
    HashSet<String> interactionsDone = new HashSet<>();

    progressManager.nextMajorStep(symManager.getQueryContainers().size());

    for (MISymContainer container : symManager.getQueryContainers()) {

        logAndPublish(container.getEntry().getGeneName());

        if (null == container.getEntry()) {
            continue;
        }

        if (null == container.getResultSym()) {
            continue;
        }

        String queryUniprotAc = container.getEntry().getUniprotAc();

        if (null == uniprotAc2uniprotAcs.get(queryUniprotAc)) {
            continue;
        }

        if (MICommons.getInstance().isBlackListed(queryUniprotAc)) {
            continue;
        }

        for (String targetUniprotAc : uniprotAc2uniprotAcs.get(queryUniprotAc)) {

            if (MICommons.getInstance().isBlackListed(targetUniprotAc)) {
                continue;
            }

            // An interaction may be slected twice, as A-B and B-A,
            // avoid this.
            if (interactionsDone.contains(targetUniprotAc + "#" + queryUniprotAc)
                    || interactionsDone.contains(queryUniprotAc + "#" + targetUniprotAc)) {
                continue;
            }
            interactionsDone.add(queryUniprotAc + "#" + targetUniprotAc);

            MISymContainer targetContainer = symManager.getByProteinAc(targetUniprotAc);

            if (targetContainer == null) {
                continue;
            }

            if (targetContainer.getEntry() == null) {
                continue;
            }

            if (targetContainer.getResultSym() == null) {
                continue;
            }

            MIResult result = new MIResult(trackId, container, targetContainer,
                    interactors.getOrCreateInteraction(container.getEntry().getUniprotAc(),
                            targetContainer.getEntry().getUniprotAc()),
                    query, symManager);

            resultsInBackground.add(result);
            miSymmetries.add(targetContainer.getResultSym());
        }

        progressManager.nextStep();

        setProgress(progressManager.getProgress());
    }

    AAPositionManager.removeManager(query.getLabel());

    return resultsInBackground;

}

From source file:uk.ac.ebi.intact.editor.controller.curate.AnnotatedObjectController.java

public void removeAlias(String alias, String aliasMI, String text, Collection<Alias> aliases) {
    if (text == null) {
        throw new IllegalArgumentException("Impossible to replace or create aliases if the name is not set.");
    }//from  w w w . j a  v a 2  s . c  o  m

    // modify if exists
    Collection<Alias> existingAliases = AliasUtils.collectAllAliasesHavingTypeAndName(aliases, aliasMI, alias,
            text);
    aliases.removeAll(existingAliases);
    setUnsavedChanges(true);
}

From source file:uk.ac.ebi.intact.editor.controller.curate.AnnotatedObjectController.java

public void removeAnnotation(String topic, String topicMI, Collection<Annotation> annots) {
    if (topic == null) {
        throw new IllegalArgumentException(
                "Impossible to replace or create annotations if the topic is not set.");
    }//w ww.j  a v a2s  . c o  m

    // modify if exists
    Collection<Annotation> existingAnnots = AnnotationUtils.collectAllAnnotationsHavingTopic(annots, topicMI,
            topic);
    annots.removeAll(existingAnnots);
    setUnsavedChanges(true);
}

From source file:uk.ac.ebi.intact.editor.controller.curate.AnnotatedObjectController.java

protected void removeXref(String database, String databaseMI, String qualifier, String qualifierMI,
        Collection<Xref> refs) {
    if (database == null) {
        throw new IllegalArgumentException(
                "Impossible to replace or create cross references if the database is not set.");
    }/*from   w  ww.ja  v a2 s . c o  m*/

    // modify if exists
    Collection<Xref> existingRefs = XrefUtils.collectAllXrefsHavingDatabaseAndQualifier(refs, databaseMI,
            database, qualifierMI, qualifier);
    refs.removeAll(existingRefs);
    setUnsavedChanges(true);
}

From source file:org.cgiar.ccafs.marlo.action.projects.ProjectLocationAction.java

@Override
public void prepare() throws Exception {

    loggedCrp = (GlobalUnit) this.getSession().get(APConstants.SESSION_CRP);
    loggedCrp = crpManager.getGlobalUnitById(loggedCrp.getId());

    projectID = Long/* w w w .  j  a  v  a2s  .  c  o  m*/
            .parseLong(StringUtils.trim(this.getRequest().getParameter(APConstants.PROJECT_REQUEST_ID)));

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

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

        if (history != null) {
            project = history;
        } else {
            this.transaction = null;

            this.setTransaction("-1");
        }

    } else {
        project = projectManager.getProjectById(projectID);
    }
    this.locationLevels();
    if (project != 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();

            project = (Project) autoSaveReader.readFromJson(jReader);
            Project projectDb = projectManager.getProjectById(project.getId());
            project.getProjectInfo().setProjectEditLeader(
                    projectDb.getProjecInfoPhase(this.getActualPhase()).isProjectEditLeader());
            // project.setProjectLocations(projectDb.getProjectLocations());
            project.getProjectInfo()
                    .setAdministrative(projectDb.getProjecInfoPhase(this.getActualPhase()).getAdministrative());
            if (project.getLocationsData() != null) {
                for (CountryLocationLevel level : project.getLocationsData()) {
                    LocElementType elementType = locElementTypeManager.getLocElementTypeById(level.getId());
                    if (elementType.getId() == 2 || elementType.getCrp() != null) {
                        level.setAllElements(elementType.getLocElements().stream().filter(le -> le.isActive())
                                .collect(Collectors.toList()));
                    }
                }

            }
            if (project.getProjectRegions() != null) {
                for (ProjectLocation projectLocation : project.getProjectRegions()) {
                    if (projectLocation.getLocElement() != null
                            && projectLocation.getLocElement().getId() != null) {
                        projectLocation.setLocElement(
                                locElementManager.getLocElementById(projectLocation.getLocElement().getId()));
                        projectLocation.setLocElementType(null);
                    } else {
                        projectLocation.setLocElementType(locElementTypeManager
                                .getLocElementTypeById(projectLocation.getLocElementType().getId()));
                        projectLocation.setLocElement(null);
                    }
                }
            }

            List<CountryFundingSources> reCountryFundingSources = new ArrayList<>();
            List<CountryFundingSources> coCountryFundingSources = new ArrayList<>();
            if (project.getRegionFS() != null) {
                for (CountryFundingSources co : project.getRegionFS()) {
                    if (co.getLocElement() != null) {
                        co.setLocElement(locElementManager.getLocElementById(co.getLocElement().getId()));
                        List<FundingSource> sources = fundingSourceManager.searchFundingSourcesByLocElement(
                                projectID, co.getLocElement().getId(), this.getCurrentCycleYear(),
                                loggedCrp.getId(), this.getActualPhase().getId());
                        for (FundingSource fundingSource : sources) {
                            fundingSource.getFundingSourceInfo(this.getActualPhase());
                        }
                        co.setFundingSources(sources);
                    } else {
                        co.setLocElementType(
                                locElementTypeManager.getLocElementTypeById(co.getLocElementType().getId()));
                        List<FundingSource> sources = fundingSourceManager.searchFundingSourcesByLocElementType(
                                projectID, co.getLocElementType().getId(), this.getCurrentCycleYear(),
                                loggedCrp.getId());
                        for (FundingSource fundingSource : sources) {
                            fundingSource.getFundingSourceInfo(this.getActualPhase());
                        }
                        co.setFundingSources(sources);
                    }
                    if (!co.isSelected()) {
                        if (co.getLocElement() != null) {
                            co.setSelected(this.locElementSelected(co.getLocElement().getId()));
                        } else {
                            co.setSelected(this.locElementTypeSelected(co.getLocElementType().getId()));
                        }
                    }
                    if (!co.getFundingSources().stream()
                            .filter(c -> c.isActive() && c.getProjectBudgets().stream()
                                    .filter(fp -> fp.isActive() && fp.getProject().isActive()
                                            && fp.getProject().getId().longValue() == projectID)
                                    .collect(Collectors.toList()).size() > 0)
                            .collect(Collectors.toList()).isEmpty()) {
                        reCountryFundingSources.add(co);
                    }

                }
            }
            project.setRegionFS(reCountryFundingSources);
            if (project.getCountryFS() != null) {
                for (CountryFundingSources co : project.getCountryFS()) {
                    if (co.getLocElement() != null) {
                        co.setLocElement(locElementManager.getLocElementById(co.getLocElement().getId()));

                        List<FundingSource> sources = fundingSourceManager.searchFundingSourcesByLocElement(
                                projectID, co.getLocElement().getId(), this.getCurrentCycleYear(),
                                loggedCrp.getId(), this.getActualPhase().getId());
                        for (FundingSource fundingSource : sources) {
                            fundingSource.getFundingSourceInfo(this.getActualPhase());
                        }
                        co.setFundingSources(new ArrayList<>(sources));

                    } else {
                        co.setLocElementType(
                                locElementTypeManager.getLocElementTypeById(co.getLocElementType().getId()));
                    }
                    if (!co.isSelected()) {
                        if (co.getLocElement() != null) {
                            co.setSelected(this.locElementSelected(co.getLocElement().getId()));
                        } else {
                            co.setSelected(this.locElementTypeSelected(co.getLocElementType().getId()));
                        }
                    }
                    if (!co.getFundingSources().stream()
                            .filter(c -> c.isActive() && c.getProjectBudgets().stream()
                                    .filter(fp -> fp.isActive() && fp.getProject().isActive()
                                            && fp.getProject().getId().longValue() == projectID)
                                    .collect(Collectors.toList()).size() > 0)
                            .collect(Collectors.toList()).isEmpty()) {
                        coCountryFundingSources.add(co);
                    }
                }
                project.setCountryFS(coCountryFundingSources);
            }

            this.prepareFundingList();
            this.setDraft(true);
        } else {
            this.setDraft(false);

            this.prepareFundingList();

            for (CountryFundingSources locElement : project.getCountryFS()) {
                locElement.setSelected(this.locElementSelected(locElement.getLocElement().getId()));
            }
            for (CountryFundingSources locElement : project.getRegionFS()) {
                if (locElement.getLocElement() != null) {
                    locElement.setSelected(this.locElementSelected(locElement.getLocElement().getId()));
                } else {
                    locElement.setSelected(this.locElementTypeSelected(locElement.getLocElementType().getId()));
                }

            }
            project.setLocationsData(this.getProjectLocationsData());
            project.setProjectRegions(new ArrayList<ProjectLocation>(this.getDBLocations().stream()
                    .filter(p -> p.isActive() && p.getLocElementType() == null && p.getLocElement() != null
                            && p.getLocElement().getLocElementType().getId().longValue() == 1
                            && p.getPhase() != null && p.getPhase().equals(this.getActualPhase()))
                    .collect(Collectors.toList())));
            project.getProjectRegions()
                    .addAll(this.getDBLocations().stream()
                            .filter(p -> p.isActive() && p.getLocElementType() != null
                                    && p.getLocElement() == null && p.getPhase().equals(this.getActualPhase()))
                            .collect(Collectors.toList()));

        }
    }

    this.listScopeRegions();

    Collection<LocElement> fsLocs = new ArrayList<>();

    if (project.getCountryFS() == null) {
        project.setCountryFS(new ArrayList<>());
    }
    if (project.getRegionFS() == null) {
        project.setRegionFS(new ArrayList<>());
    }

    for (CountryFundingSources locElement : project.getCountryFS()) {
        fsLocs.add(locElement.getLocElement());
    }

    if (project.getLocationsData() == null) {
        project.setLocationsData(new ArrayList<>());
    }

    // Fix Ull Collection when autosave gets the suggeste country - 10/13/2017
    for (CountryLocationLevel countryLocationLevel : project.getLocationsData()) {
        if (countryLocationLevel.getLocElements() != null) {
            Collection<LocElement> similar = new HashSet<LocElement>(countryLocationLevel.getLocElements());
            Collection<LocElement> different = new HashSet<LocElement>();
            different.addAll(countryLocationLevel.getLocElements());
            different.addAll(fsLocs);
            similar.retainAll(fsLocs);
            different.removeAll(similar);

            countryLocationLevel.getLocElements().removeAll(similar);
        }

    }

    Collection<LocElement> fsLocsRegions = new ArrayList<>();
    for (CountryFundingSources locElement : project.getRegionFS()) {
        if (locElement.getLocElement() != null) {
            fsLocsRegions.add(locElement.getLocElement());
        }

    }

    if (project.getProjectRegions() != null) {
        for (ProjectLocation projectLocation : project.getProjectRegions().stream()
                .filter(c -> c.getLocElement() != null).collect(Collectors.toList())) {

            if (fsLocsRegions.contains(projectLocation.getLocElement())) {
                project.getProjectRegions().remove(projectLocation);
            }

        }
    }

    Collection<LocElementType> fsLocsCustomRegions = new ArrayList<>();
    for (CountryFundingSources locElement : project.getRegionFS()) {
        if (locElement.getLocElementType() != null) {
            fsLocsCustomRegions.add(locElement.getLocElementType());

        }

    }

    if (project.getProjectRegions() != null) {
        for (ProjectLocation projectLocation : project.getProjectRegions().stream()
                .filter(c -> c.getLocElementType() != null).collect(Collectors.toList())) {

            if (fsLocsCustomRegions.contains(projectLocation.getLocElementType())) {
                project.getProjectRegions().remove(projectLocation);
            }

        }
    }

    regionLists = new ArrayList<>(locElementManager.findAll().stream().filter(
            le -> le.isActive() && le.getLocElementType() != null && le.getLocElementType().getId() == 1)
            .collect(Collectors.toList()));
    Collections.sort(regionLists, (r1, r2) -> r1.getName().compareTo(r2.getName()));
    scopeRegionLists = new ArrayList<>(locElementTypeManager.findAll().stream()
            .filter(le -> le.isActive() && le.getCrp() != null && le.getCrp().equals(loggedCrp) && le.isScope())
            .collect(Collectors.toList()));
    String params[] = { loggedCrp.getAcronym(), project.getId() + "" };
    this.setBasePermission(this.getText(Permission.PROJECT_LOCATION_BASE_PERMISSION, params));

    if (!project.getLocationsData().stream().filter(c -> c.getId().longValue() != 2)
            .collect(Collectors.toList()).isEmpty()) {
        region = true;
    } else {
        region = false;
    }
    if (this.isHttpPost()) {
        if (project.getLocationsData() != null) {
            project.getLocationsData().clear();
        }

        project.getProjecInfoPhase(this.getActualPhase()).setLocationGlobal(false);
        if (project.getCountryFS() != null) {
            project.getCountryFS().clear();
        }
        if (project.getRegionFS() != null) {
            project.getRegionFS().clear();
        }
        if (project.getRegions() != null) {
            project.getRegions().clear();
        }
        if (project.getProjectRegions() != null) {
            project.getProjectRegions().clear();
        }

    }

}

From source file:nl.strohalm.cyclos.services.groups.GroupServiceImpl.java

@SuppressWarnings("unchecked")
private <G extends Group> G save(G group) {
    if (group.isTransient()) {
        group = groupDao.insert(group);/*from   w ww  .j  ava 2s .co m*/
    } else {
        // We must keep the many-to-many relationships, or they would be cleared...
        final Group currentGroup = load(group.getId(), FETCH_TO_KEEP_DATA);

        group.setPermissions(new HashSet<Permission>(currentGroup.getPermissions()));
        group.setTransferTypes(new ArrayList<TransferType>(currentGroup.getTransferTypes()));
        group.setConversionSimulationTTs(
                new ArrayList<TransferType>(currentGroup.getConversionSimulationTTs()));
        group.setGuaranteeTypes(new ArrayList<GuaranteeType>(currentGroup.getGuaranteeTypes()));

        if (group instanceof SystemGroup) {
            final SystemGroup systemGroup = (SystemGroup) group;
            final SystemGroup currentSystemGroup = ((SystemGroup) currentGroup);
            systemGroup.setDocuments(new ArrayList<Document>(currentSystemGroup.getDocuments()));
            systemGroup.setMessageCategories(
                    new ArrayList<MessageCategory>(currentSystemGroup.getMessageCategories()));
            systemGroup.setChargebackTransferTypes(
                    new ArrayList<TransferType>(currentSystemGroup.getChargebackTransferTypes()));
        }

        if (group instanceof AdminGroup) {
            final AdminGroup adminGroup = (AdminGroup) group;
            final AdminGroup currentAdminGroup = ((AdminGroup) currentGroup);
            adminGroup.setTransferTypesAsMember(
                    new ArrayList<TransferType>(currentAdminGroup.getTransferTypesAsMember()));
            adminGroup.setManagesGroups(new ArrayList<MemberGroup>(currentAdminGroup.getManagesGroups()));
            adminGroup.setViewConnectedAdminsOf(
                    new ArrayList<AdminGroup>(currentAdminGroup.getViewConnectedAdminsOf()));
            adminGroup.setViewInformationOf(
                    new ArrayList<SystemAccountType>(currentAdminGroup.getViewInformationOf()));
            adminGroup.setViewAdminRecordTypes(
                    new ArrayList<MemberRecordType>(currentAdminGroup.getViewAdminRecordTypes()));
            adminGroup.setCreateAdminRecordTypes(
                    new ArrayList<MemberRecordType>(currentAdminGroup.getCreateAdminRecordTypes()));
            adminGroup.setModifyAdminRecordTypes(
                    new ArrayList<MemberRecordType>(currentAdminGroup.getModifyAdminRecordTypes()));
            adminGroup.setDeleteAdminRecordTypes(
                    new ArrayList<MemberRecordType>(currentAdminGroup.getDeleteAdminRecordTypes()));
            adminGroup.setViewMemberRecordTypes(
                    new ArrayList<MemberRecordType>(currentAdminGroup.getViewMemberRecordTypes()));
            adminGroup.setCreateMemberRecordTypes(
                    new ArrayList<MemberRecordType>(currentAdminGroup.getCreateMemberRecordTypes()));
            adminGroup.setModifyMemberRecordTypes(
                    new ArrayList<MemberRecordType>(currentAdminGroup.getModifyMemberRecordTypes()));
            adminGroup.setDeleteMemberRecordTypes(
                    new ArrayList<MemberRecordType>(currentAdminGroup.getDeleteMemberRecordTypes()));
        }
        if (group instanceof BrokerGroup) {
            final BrokerGroup brokerGroup = (BrokerGroup) group;
            final BrokerGroup currentBrokerGroup = (BrokerGroup) currentGroup;

            final List<Document> brokerDocuments = new ArrayList<Document>();
            if (currentBrokerGroup.getBrokerDocuments() != null) {
                brokerDocuments.addAll(currentBrokerGroup.getBrokerDocuments());
            }
            brokerGroup.setBrokerDocuments(brokerDocuments);

            final List<AccountType> brokerCanViewInformationOf = new ArrayList<AccountType>();
            if (brokerGroup.getBrokerCanViewInformationOf() != null) {
                brokerCanViewInformationOf.addAll(brokerGroup.getBrokerCanViewInformationOf());
            }
            brokerGroup.setBrokerCanViewInformationOf(brokerCanViewInformationOf);

            brokerGroup.setTransferTypesAsMember(
                    new ArrayList<TransferType>(currentBrokerGroup.getTransferTypesAsMember()));
            brokerGroup.setBrokerConversionSimulationTTs(
                    new ArrayList<TransferType>(currentBrokerGroup.getBrokerConversionSimulationTTs()));
            brokerGroup.setBrokerMemberRecordTypes(
                    new ArrayList<MemberRecordType>(currentBrokerGroup.getBrokerMemberRecordTypes()));
            brokerGroup.setBrokerCreateMemberRecordTypes(
                    new ArrayList<MemberRecordType>(currentBrokerGroup.getBrokerCreateMemberRecordTypes()));
            brokerGroup.setBrokerModifyMemberRecordTypes(
                    new ArrayList<MemberRecordType>(currentBrokerGroup.getBrokerModifyMemberRecordTypes()));
            brokerGroup.setBrokerDeleteMemberRecordTypes(
                    new ArrayList<MemberRecordType>(currentBrokerGroup.getBrokerDeleteMemberRecordTypes()));

            // "possibleInitialGroups" is updated at edit group screen, so it doesn't need to be copied
        }
        if (group instanceof MemberGroup) {
            final MemberGroup memberGroup = (MemberGroup) group;
            final MemberGroup currentMemberGroup = (MemberGroup) currentGroup;
            memberGroup.setAccountSettings(currentMemberGroup.getAccountSettings());

            // Ensure that no channel will be set by default if it's not accessible
            memberGroup.getDefaultChannels().retainAll(memberGroup.getChannels());

            // Ensure the removedChannels collection contains the channels which were removed
            final Collection<Channel> removedChannels = new HashSet<Channel>();
            removedChannels.addAll(currentMemberGroup.getChannels());
            removedChannels.removeAll(memberGroup.getChannels());

            final List<MemberGroup> viewProfile = new ArrayList<MemberGroup>();
            if (currentMemberGroup.getCanViewProfileOfGroups() != null) {
                viewProfile.addAll(currentMemberGroup.getCanViewProfileOfGroups());
            }
            memberGroup.setCanViewProfileOfGroups(viewProfile);

            final List<AccountType> canViewInformationOf = new ArrayList<AccountType>();
            if (currentMemberGroup.getCanViewInformationOf() != null) {
                canViewInformationOf.addAll(currentMemberGroup.getCanViewInformationOf());
            }
            memberGroup.setCanViewInformationOf(canViewInformationOf);

            final List<MemberGroup> viewAds = new ArrayList<MemberGroup>();
            if (currentMemberGroup.getCanViewAdsOfGroups() != null) {
                viewAds.addAll(currentMemberGroup.getCanViewAdsOfGroups());
            }
            memberGroup.setCanViewAdsOfGroups(viewAds);

            final List<AdminGroup> managedByGroups = new ArrayList<AdminGroup>();
            if (currentMemberGroup.getManagedByGroups() != null) {
                managedByGroups.addAll(currentMemberGroup.getManagedByGroups());
            }
            memberGroup.setManagedByGroups(managedByGroups);

            // "defaultMailMessages" is updated at edit group screen, so it doesn't need to be copied
            // "smsMessages" is updated at edit group screen, so it doesn't need to be copied
            // "defaultSmsMessages" is updated at edit group screen, so it doesn't need to be copied
            // "channels" is updated at edit group screen, so it doesn't need to be copied
            // "defaultChannels" is updated at edit group screen, so it doesn't need to be copied

            // Add the main web access to default and accessible channels.
            final Channel webChannel = channelService.loadByInternalName(Channel.WEB);
            memberGroup.setChannels(
                    CollectionUtils.union(memberGroup.getChannels(), Collections.singleton(webChannel)));
            memberGroup.setDefaultChannels(
                    CollectionUtils.union(memberGroup.getDefaultChannels(), Collections.singleton(webChannel)));

            final List<Channel> requestPaymentByChannels = new ArrayList<Channel>();
            if (currentMemberGroup.getRequestPaymentByChannels() != null) {
                requestPaymentByChannels.addAll(currentMemberGroup.getRequestPaymentByChannels());
            }
            memberGroup.setRequestPaymentByChannels(requestPaymentByChannels);

            final MemberGroupSettings memberSettings = memberGroup.getMemberSettings();
            memberSettings
                    .setGroupAfterExpiration(fetchService.fetch(memberSettings.getGroupAfterExpiration()));

            // Update the basic settings of operator groups for members in this group
            final GroupQuery operatorQuery = new GroupQuery();
            operatorQuery.setNature(Group.Nature.OPERATOR);
            operatorQuery.fetch(
                    RelationshipHelper.nested(OperatorGroup.Relationships.MEMBER, Element.Relationships.GROUP));
            final List<OperatorGroup> operatorGroups = (List<OperatorGroup>) groupDao.search(operatorQuery);
            for (final OperatorGroup operatorGroup : operatorGroups) {
                if (operatorGroup.getMember().getGroup().equals(memberGroup)) {
                    groupDao.update(operatorGroup);
                }
            }
            final List<MemberGroup> canIssueCertificationToGroups = new ArrayList<MemberGroup>();
            if (currentMemberGroup.getCanIssueCertificationToGroups() != null) {
                canIssueCertificationToGroups.addAll(currentMemberGroup.getCanIssueCertificationToGroups());
            }
            memberGroup.setCanIssueCertificationToGroups(canIssueCertificationToGroups);

            final List<MemberGroup> canBuyWithPaymentObligationsFromGroups = new ArrayList<MemberGroup>();
            if (currentMemberGroup.getCanBuyWithPaymentObligationsFromGroups() != null) {
                canBuyWithPaymentObligationsFromGroups
                        .addAll(currentMemberGroup.getCanBuyWithPaymentObligationsFromGroups());
            }
            memberGroup.setCanBuyWithPaymentObligationsFromGroups(canBuyWithPaymentObligationsFromGroups);

            // Ensure the message notification types are not present on the group for SMS
            final Collection<Message.Type> smsMessages = memberGroup.getSmsMessages();
            if (smsMessages != null) {
                smsMessages.remove(Message.Type.FROM_MEMBER);
                smsMessages.remove(Message.Type.FROM_ADMIN_TO_GROUP);
                smsMessages.remove(Message.Type.FROM_ADMIN_TO_MEMBER);
            }
            final Collection<Type> defaultSmsMessages = memberGroup.getDefaultSmsMessages();
            if (defaultSmsMessages != null) {
                defaultSmsMessages.remove(Message.Type.FROM_MEMBER);
                defaultSmsMessages.remove(Message.Type.FROM_ADMIN_TO_GROUP);
                defaultSmsMessages.remove(Message.Type.FROM_ADMIN_TO_MEMBER);
            }

            // Remove from all members channels which are no longer accessible
            elementDao.removeChannelsFromMembers(memberGroup, removedChannels);

            // ensure activation status
            if (memberGroup.isRemoved()) {
                memberGroup.setActive(false);
            }
        }
        if (group instanceof OperatorGroup) {
            final OperatorGroup operatorGroup = (OperatorGroup) group;
            final OperatorGroup currentOperatorGroup = (OperatorGroup) currentGroup;

            // Check the account types
            final List<AccountType> canViewInformationOf = new ArrayList<AccountType>();
            if (currentOperatorGroup.getCanViewInformationOf() != null) {
                canViewInformationOf.addAll(currentOperatorGroup.getCanViewInformationOf());
            }
            operatorGroup.setCanViewInformationOf(canViewInformationOf);
        }
        group = groupDao.update(group);
    }
    // Ensure the permissions cache for this group is evicted
    permissionService.evictCache(group);
    return group;
}

From source file:ubic.gemma.persistence.service.expression.experiment.GeeqServiceImpl.java

/**
 * Checks for all combinations of factor values in the experiments bio assays, and counts the amount of
 * their occurrences, then checks what the lowest amount is. The method only combines factor values from
 * first (up to) MAX_EFS_REPLICATE_CHECK categorical experimental factors it encounters, and always disregards
 * values from batch factors./*from w  w w  .j  a va2  s  . c om*/
 *
 * @param  ee an expression experiment to get the count for.
 * @return    the lowest number of replicates (ignoring factor value combinations with only one replicate),
 *            or -2 if <em>all</em> factor value combinations were present only once, or -1, if there were no usable
 *            factors
 *            to begin with.
 */
private int leastReplicates(ExpressionExperiment ee) {
    HashMap<String, Integer> factors = new HashMap<>();
    Collection<BioAssay> bas = ee.getBioAssays();
    List<ExperimentalFactor> keepEfs = new ArrayList<>(GeeqServiceImpl.MAX_EFS_REPLICATE_CHECK);

    for (BioAssay ba : bas) {
        Collection<FactorValue> fvs = ba.getSampleUsed().getFactorValues();

        //only keep up to MAX_EFS_REPLICATE_CHECK categorical factors, ignoring batch factor and DE_EXCLUDE
        Collection<FactorValue> removeFvs = new LinkedList<>();
        for (FactorValue fv : fvs) {
            ExperimentalFactor ef = fv.getExperimentalFactor();
            if (ExperimentalDesignUtils.isBatch(ef) || DE_EXCLUDE.equalsIgnoreCase(fv.getDescriptiveString())
                    || ef.getType().equals(FactorType.CONTINUOUS)) {
                removeFvs.add(fv); // always remove batch factor values and DE_EXCLUDE values
            } else {
                if (!keepEfs.contains(ef) && keepEfs.size() <= GeeqServiceImpl.MAX_EFS_REPLICATE_CHECK) {
                    keepEfs.add(ef); // keep first MAX_EFS_REPLICATE_CHECK encountered factors
                } else if (!keepEfs.contains(ef)) {
                    removeFvs.add(fv); // if from different factor, remove the value
                }
            }
        }
        fvs.removeAll(removeFvs);

        // sort so the keys in the hash map are consistent
        Collection<Long> ids = EntityUtils.getIds(fvs);
        Long[] arr = ids.toArray(new Long[0]);
        Arrays.sort(arr);
        String key = Arrays.toString(arr);

        // add new key or increment counter of existing one
        Integer cnt = factors.get(key);
        factors.put(key, cnt == null ? 1 : ++cnt);
    }

    List<Integer> counts = new ArrayList<>(factors.values());
    Collections.sort(counts);

    if (counts.isEmpty()) {
        return -1;
    } else if (counts.get(counts.size() - 1) == 1) {
        return -2; // all conditions have only one replicate
    } else {
        return counts.get(0);
    }

}

From source file:org.sipfoundry.openfire.plugin.presence.SipXOpenfirePlugin.java

public void update(XmppGroup group) throws GroupAlreadyExistsException, GroupNotFoundException {
    log.debug("update Group " + group.getGroupName());

    boolean isAllAdminGroup = false;
    String adminJid = null;/*  w  w w.j a v a 2  s . c  o  m*/
    JID adminJID = null;
    if (group.getAdministrator() != null && !group.getAdministrator().isEmpty()) {
        adminJid = XmppAccountInfo.appendDomain(group.getAdministrator());
        adminJID = new JID(adminJid);
    } else {
        isAllAdminGroup = true;

    }

    // check if group already exists in openfire
    try {
        Group openfireGroup = getGroupByName(group.getGroupName());

        // enforce description in case it changed
        openfireGroup.setDescription(group.getDescription());

        // group already exists, make sure that it contains the correct set of members.
        // This is achieved in two operations:
        //  1- Add all members that are currently not in the group but are found in the group from configuration file
        //  2- Remove all members that are currently in the group but not found in the group from configuration file
        log.info("create Group: " + group.getGroupName() + " already exists - enforce members list");
        Collection<String> currentGroupMembers = new HashSet<String>();
        for (JID jid : openfireGroup.getMembers()) {
            currentGroupMembers.add(jid.toBareJID());
        }

        Collection<String> desiredGroupMembers = new HashSet<String>();
        Collection<String> desiredGroupMembersBackup = new HashSet<String>();
        for (XmppGroupMember member : group.getMembers()) {
            desiredGroupMembers.add(member.getJid());
            desiredGroupMembersBackup.add(member.getJid());
        }

        //  1- Add all members that are currently not in the group but are found in the group from configuration file
        desiredGroupMembers.removeAll(currentGroupMembers);
        log.info("Need to add the following members to group '" + group.getGroupName() + "': "
                + desiredGroupMembers);
        for (String jid : desiredGroupMembers) {
            addUserToGroup(jid, group.getGroupName(), isAllAdminGroup);
        }

        //  2- Remove all members that are currently in the group but not found in the group from configuration file
        currentGroupMembers.removeAll(desiredGroupMembersBackup);
        log.info("Need to remove the following members to group '" + group.getGroupName() + "': "
                + currentGroupMembers);
        for (String jid : currentGroupMembers) {
            removeUserFromGroup(jid, group.getGroupName());
        }

    } catch (GroupNotFoundException ex) {
        log.info("Group: " + group.getGroupName() + " does not exist - create it");
        Group openfireGroup = groupManager.createGroup(group.getGroupName());
        if (group.getDescription() != null) {
            openfireGroup.setDescription(group.getDescription());
        }

        if (adminJID != null && adminJID.getDomain().equals(this.getXmppDomain())
                && this.isValidUser(adminJID)) {
            openfireGroup.getAdmins().add(adminJID);
        }

        // configure group as 'shared' among group members
        // (magic recipe taken from 'AddGroup.java file of openfire project)
        openfireGroup.getProperties().put("sharedRoster.showInRoster", "onlyGroup");
        openfireGroup.getProperties().put("sharedRoster.displayName", group.getGroupName());

        // add members to the group
        for (XmppGroupMember member : group.getMembers()) {
            String userJid = XmppAccountInfo.appendDomain(member.getJid());
            addUserToGroup(userJid, group.getGroupName(), isAllAdminGroup);
        }
    }
}

From source file:uk.ac.ebi.intact.dbupdate.prot.actions.impl.ProtWithoutInteractionDeleterImpl.java

/**
 * For each protein transcript to review, check if it has interactions attached to it. If no
 * add the protein transcript to the list of proteins to delete
 * @param protToInspect : list of protein transcripts to review
 * @param protToDelete : list of protein transcripts to delete
 * @param evt/*from www  . j  av  a  2  s.  c om*/
 */
private void collectProteinsTranscriptsWithoutInteractionsFrom(Collection<ProteinTranscript> protToInspect,
        Set<Protein> protToDelete, UpdateCaseEvent evt) {
    ProteinUpdateProcessorConfig config = ProteinUpdateContext.getInstance().getConfig();
    ProteinUpdateErrorFactory errorFactory = config.getErrorFactory();

    Collection<ProteinTranscript> transcriptToDelete = new ArrayList<ProteinTranscript>();

    for (ProteinTranscript p : protToInspect) {
        if (p.getProtein().getAc() == null) {
            log.debug("Protein without AC, cannot be deleted");
            if (evt.getSource() instanceof ProteinUpdateProcessor) {
                final ProteinUpdateProcessor updateProcessor = (ProteinUpdateProcessor) evt.getSource();

                ProteinUpdateError impossibleToDelete = errorFactory.createImpossibleToDeleteError(
                        p.getProtein().getShortLabel(), "The protein " + p.getProtein().getShortLabel()
                                + " cannot be deleted because doesn't have any intact ac.");
                updateProcessor.fireOnProcessErrorFound(new UpdateErrorEvent(updateProcessor,
                        evt.getDataContext(), impossibleToDelete, p.getProtein(), evt.getQuerySentToService()));
            }
        } else {

            final Integer interactionCount = p.getProtein().getActiveInstances().size();

            if (interactionCount == 0) {

                if (log.isDebugEnabled())
                    log.debug("Protein transcript will be deleted: " + p.getProtein().getAc());
                protToDelete.add(p.getProtein());
                transcriptToDelete.add(p);
            }
        }
    }

    protToInspect.removeAll(transcriptToDelete);
}