Example usage for java.util HashMap putAll

List of usage examples for java.util HashMap putAll

Introduction

In this page you can find the example usage for java.util HashMap putAll.

Prototype

public void putAll(Map<? extends K, ? extends V> m) 

Source Link

Document

Copies all of the mappings from the specified map to this map.

Usage

From source file:org.moqui.impl.service.ServiceDefinition.java

@SuppressWarnings("unchecked")
private Map<String, Object> nestedParameterClean(String namePrefix, Map<String, Object> parameters,
        ParameterInfo[] parameterInfoArray, ExecutionContextImpl eci) {
    HashMap<String, Object> newMap = new HashMap<>();
    for (int i = 0; i < parameterInfoArray.length; i++) {
        ParameterInfo parameterInfo = parameterInfoArray[i];
        String parameterName = parameterInfo.name;

        boolean hasParameter = parameters.containsKey(parameterName);
        Object parameterValue = hasParameter ? parameters.remove(parameterName) : null;

        boolean parameterIsEmpty;
        boolean isString = false;
        boolean isCollection = false;
        boolean isMap = false;
        Class parameterClass = null;
        if (parameterValue != null) {
            if (parameterValue instanceof CharSequence) {
                String stringValue = parameterValue.toString();
                parameterValue = stringValue;
                isString = true;//  w w w.  ja va 2s.com
                parameterClass = String.class;
                parameterIsEmpty = stringValue.isEmpty();
            } else {
                parameterClass = parameterValue.getClass();
                if (parameterValue instanceof Map) {
                    isMap = true;
                    parameterIsEmpty = ((Map) parameterValue).isEmpty();
                } else if (parameterValue instanceof Collection) {
                    isCollection = true;
                    parameterIsEmpty = ((Collection) parameterValue).isEmpty();
                } else {
                    parameterIsEmpty = false;
                }
            }
        } else {
            parameterIsEmpty = true;
        }

        // set the default if applicable
        if (parameterIsEmpty) {
            if (parameterInfo.hasDefault) {
                // TODO: consider doing this as a second pass so newMap has all parameters
                if (parameterInfo.defaultStr != null) {
                    Map<String, Object> combinedMap = new HashMap<>(parameters);
                    combinedMap.putAll(newMap);
                    parameterValue = eci.resourceFacade.expression(parameterInfo.defaultStr, null, combinedMap);
                    if (parameterValue != null) {
                        hasParameter = true;
                        isString = false;
                        isCollection = false;
                        isMap = false;
                        if (parameterValue instanceof CharSequence) {
                            String stringValue = parameterValue.toString();
                            parameterValue = stringValue;
                            isString = true;
                            parameterClass = String.class;
                            parameterIsEmpty = stringValue.isEmpty();
                        } else {
                            parameterClass = parameterValue.getClass();
                            if (parameterValue instanceof Map) {
                                isMap = true;
                                parameterIsEmpty = ((Map) parameterValue).isEmpty();
                            } else if (parameterValue instanceof Collection) {
                                isCollection = true;
                                parameterIsEmpty = ((Collection) parameterValue).isEmpty();
                            } else {
                                parameterIsEmpty = false;
                            }
                        }
                    }
                } else if (parameterInfo.defaultValue != null) {
                    String stringValue;
                    if (parameterInfo.defaultValueNeedsExpand) {
                        Map<String, Object> combinedMap = new HashMap<>(parameters);
                        combinedMap.putAll(newMap);
                        stringValue = eci.resourceFacade.expand(parameterInfo.defaultValue, null, combinedMap,
                                false);
                    } else {
                        stringValue = parameterInfo.defaultValue;
                    }
                    hasParameter = true;
                    parameterValue = stringValue;
                    isString = true;
                    parameterClass = String.class;
                    parameterIsEmpty = stringValue.isEmpty();
                }
            } else {
                // if empty but not null and types don't match set to null instead of trying to convert
                if (parameterValue != null) {
                    boolean typeMatches;
                    if (parameterInfo.parmClass != null) {
                        typeMatches = parameterClass == parameterInfo.parmClass
                                || parameterInfo.parmClass.isInstance(parameterValue);
                    } else {
                        typeMatches = StupidJavaUtilities.isInstanceOf(parameterValue, parameterInfo.type);
                    }
                    if (!typeMatches)
                        parameterValue = null;
                }
            }
            // if required and still empty (nothing from default), complain
            if (parameterIsEmpty && validate && parameterInfo.required)
                eci.messageFacade.addValidationError(null, namePrefix + parameterName, serviceName,
                        eci.getL10n().localize("Field cannot be empty"), null);
        }
        // NOTE: not else because parameterIsEmpty may be changed
        if (!parameterIsEmpty) {
            boolean typeMatches;
            if (parameterInfo.parmClass != null) {
                typeMatches = parameterClass == parameterInfo.parmClass
                        || parameterInfo.parmClass.isInstance(parameterValue);
            } else {
                typeMatches = StupidJavaUtilities.isInstanceOf(parameterValue, parameterInfo.type);
            }
            if (!typeMatches) {
                // convert type, at this point parameterValue is not empty and doesn't match parameter type
                parameterValue = parameterInfo.convertType(namePrefix, parameterValue, isString, eci);
                isString = false;
                isCollection = false;
                isMap = false;
                if (parameterValue instanceof CharSequence) {
                    parameterValue = parameterValue.toString();
                    isString = true;
                } else if (parameterValue instanceof Map) {
                    isMap = true;
                } else if (parameterValue instanceof Collection) {
                    isCollection = true;
                }
            }

            if (validate) {
                if ((isString || isCollection)
                        && ParameterInfo.ParameterAllowHtml.ANY != parameterInfo.allowHtml) {
                    Object htmlValidated = parameterInfo.validateParameterHtml(namePrefix, parameterValue,
                            isString, eci);
                    // put the final parameterValue back into the parameters Map
                    if (htmlValidated != null) {
                        parameterValue = htmlValidated;
                    }
                }

                // check against validation sub-elements (do this after the convert so we can deal with objects when needed)
                if (parameterInfo.validationNodeList != null) {
                    int valListSize = parameterInfo.validationNodeList.size();
                    for (int valIdx = 0; valIdx < valListSize; valIdx++) {
                        MNode valNode = parameterInfo.validationNodeList.get(valIdx);
                        // NOTE don't break on fail, we want to get a list of all failures for the user to see
                        try {
                            // validateParameterSingle calls eci.message.addValidationError as needed so nothing else to do here
                            validateParameterSingle(valNode, parameterName, parameterValue, eci);
                        } catch (Throwable t) {
                            logger.error("Error in validation", t);
                            Map<String, Object> map = new HashMap<>(3);
                            map.put("parameterValue", parameterValue);
                            map.put("valNode", valNode);
                            map.put("t", t);
                            eci.getMessage().addValidationError(null, parameterName, serviceName,
                                    eci.getResource().expand(
                                            "Value entered (${parameterValue}) failed ${valNode.name} validation: ${t.message}",
                                            "", map),
                                    null);
                        }
                    }
                }
            }
            if (isMap && parameterInfo.childParameterInfoArray != null
                    && parameterInfo.childParameterInfoArray.length > 0) {
                parameterValue = nestedParameterClean(namePrefix + parameterName + ".",
                        (Map<String, Object>) parameterValue, parameterInfo.childParameterInfoArray, eci);
            }
        }

        if (hasParameter)
            newMap.put(parameterName, parameterValue);
    }

    // if we are not validating and there are parameters remaining, add them to the newMap
    if (!validate && parameters.size() > 0) {
        newMap.putAll(parameters);
    }

    return newMap;
}

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  w w  w .  ja v 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:com.globalsight.webservices.Ambassador.java

/**
 * Remote leveraging./*from   w  w w. j a va 2  s .co m*/
 * 
 * @param p_accessToken
 *            Access token.
 * @param p_remoteTmProfileId
 *            Tm profile id on remote server
 * @param p_segmentMap
 *            (OriginalTuvId:Segment) map
 * @param p_sourceLocaleId
 *            Source locale Id
 * @param p_btrgLocal2LevLocalesMap
 *            (Target locale Id:leverage locales Ids with comma seperated)
 *            map
 * @param p_translatable
 *            True:translatable segments;False:localizable segments
 * @param p_escapeString
 *            If escape string.
 * @return leveraged results in map.
 * 
 * @throws WebServiceException
 */
public HashMap searchEntriesInBatch(String p_accessToken, Long p_remoteTmProfileId, Map p_segmentMap,
        Long p_sourceLocaleId, Map p_btrgLocal2LevLocalesMap, Boolean p_translatable, Boolean p_escapeString)
        throws WebServiceException {
    checkAccess(p_accessToken, "searchEntriesInBatch");
    // checkPermission(p_accessToken, Permission.SERVICE_TM_SEARCH_ENTRY);

    HashMap originalTuvId2MatchesMap = new HashMap();
    Session session = null;
    try {
        session = HibernateUtil.getSession();

        Leverager leverager = new Leverager(session);
        LocaleManager localeManager = ServerProxy.getLocaleManager();
        ProjectHandler projectHandler = ServerProxy.getProjectHandler();

        // source locale
        GlobalSightLocale sourceLocale = null;
        sourceLocale = localeManager.getLocaleById(p_sourceLocaleId);

        // target locales and leverage locales
        ArrayList trgLocales = new ArrayList();
        LeveragingLocales levLocales = new LeveragingLocales();
        if (p_btrgLocal2LevLocalesMap != null && p_btrgLocal2LevLocalesMap.size() > 0) {
            Iterator iter = p_btrgLocal2LevLocalesMap.entrySet().iterator();
            while (iter.hasNext()) {
                Map.Entry entry = (Map.Entry) iter.next();
                long trgLocaleId = ((Long) entry.getKey()).longValue();
                GlobalSightLocale trgLocale = localeManager.getLocaleById(trgLocaleId);
                trgLocales.add(trgLocale);

                String levLocaleIds = (String) entry.getValue();
                StringTokenizer st = new StringTokenizer(levLocaleIds, ",");
                while (st.hasMoreElements()) {
                    long levLocaleId = Long.parseLong((String) st.nextElement());
                    GlobalSightLocale levLocale = localeManager.getLocaleById(levLocaleId);
                    Set leveragingLocales = null;
                    try {
                        leveragingLocales = levLocales.getLeveragingLocales(levLocale);
                    } catch (Exception e) {
                    }
                    levLocales.setLeveragingLocale(levLocale, leveragingLocales);
                }
            }
        }

        // tm profile
        TranslationMemoryProfile tmp = TMProfileHandlerHelper.getTMProfileById(p_remoteTmProfileId);
        if (tmp == null) {
            String message = "Unable to get translation memory profile by id:" + p_remoteTmProfileId;
            logger.error(message);
            throw new WebServiceException(message);
        }

        ProjectTM ptm = ServerProxy.getProjectHandler().getProjectTMById(tmp.getProjectTmIdForSave(), false);
        // tmIdsOverride
        Set tmIdsOverride = new HashSet();
        Vector<LeverageProjectTM> tms = tmp.getProjectTMsToLeverageFrom();
        for (LeverageProjectTM tm : tms) {
            ProjectTM projectTm = (ProjectTM) projectHandler.getProjectTMById(tm.getProjectTmId(), false);
            if (projectTm.getIsRemoteTm() == false) {
                tmIdsOverride.add(tm.getProjectTmId());
            }
        }

        // levOptions & leverageDataCenter
        OverridableLeverageOptions levOptions = new OverridableLeverageOptions(tmp, levLocales);
        int threshold = (int) tmp.getFuzzyMatchThreshold();
        levOptions.setMatchThreshold(threshold);
        levOptions.setTmsToLeverageFrom(tmIdsOverride);
        boolean isTmProcedence = tmp.isTmProcendence();

        // find the source tuvs
        List<PageTmTuv> sourceTuvs = new ArrayList<PageTmTuv>();
        Iterator segmentsIter = p_segmentMap.entrySet().iterator();
        while (segmentsIter.hasNext()) {
            Map.Entry entry = (Map.Entry) segmentsIter.next();
            long srcTuvId = ((Long) entry.getKey()).longValue();
            String segment = (String) entry.getValue();
            segment = wrapSegment(segment, p_escapeString.booleanValue());
            PageTmTu tu = new PageTmTu(-1, -1, "plaintext", "text", p_translatable);
            PageTmTuv tuv = new PageTmTuv(srcTuvId, segment, sourceLocale);
            tuv.setTu(tu);
            tuv.setExactMatchKey();
            tu.addTuv(tuv);
            sourceTuvs.add(tuv);
        }

        // Leverage
        LeverageDataCenter leverageDataCenter = null;
        try {
            leverageDataCenter = LingServerProxy.getTmCoreManager().leverageSegments(sourceTuvs, sourceLocale,
                    trgLocales, levOptions);
        } catch (Exception e) {
            logger.error("Failed to leverage segments.", e);
        }

        Iterator itLeverageMatches = leverageDataCenter.leverageResultIterator();
        while (itLeverageMatches.hasNext()) {
            // one "LeverageMatches" represents one segment matches
            LeverageMatches levMatches = (LeverageMatches) itLeverageMatches.next();
            long originalTuvId = levMatches.getOriginalTuv().getId();
            HashMap trgLocaleMatchesMap = new HashMap();

            long jobId = -1; // -1 is fine here
            Iterator itLocales = levMatches.targetLocaleIterator(jobId);
            while (itLocales.hasNext()) {
                GlobalSightLocale targetLocale = (GlobalSightLocale) itLocales.next();
                Vector matchedTuvMapForSpecifiedTrgLocale = new Vector();

                HashMap innerMap = new HashMap();
                Iterator itMatch = levMatches.matchIterator(targetLocale, jobId);
                while (itMatch.hasNext()) {
                    LeveragedTuv matchedTuv = (LeveragedTuv) itMatch.next();

                    HashMap matchInfoMap = new HashMap();
                    String subId = ((SegmentTmTu) levMatches.getOriginalTuv().getTu()).getSubId();
                    matchInfoMap.put("subId", subId);
                    String matchedSegment = matchedTuv.getSegmentNoTopTag();
                    matchedSegment = matchedTuv.getSegment();
                    matchInfoMap.put("matchedSegment", matchedSegment);
                    String matchType = matchedTuv.getMatchState().getName();
                    matchInfoMap.put("matchType", matchType);
                    int orderNum = matchedTuv.getOrder();
                    matchInfoMap.put("orderNum", orderNum);
                    float score = matchedTuv.getScore();
                    matchInfoMap.put("score", score);
                    // source string from TM
                    ProjectTmTuvT tmTuv = HibernateUtil.get(ProjectTmTuvT.class, matchedTuv.getId());
                    String tmSource = "";
                    if (tmTuv != null) {
                        try {
                            tmSource = tmTuv.getTu().getSourceTuv().getSegmentString();
                        } catch (Exception ex) {
                        }
                    }
                    matchInfoMap.put("tmSourceStr", tmSource);
                    int matchedTableType = LeverageMatchLingManagerLocal.getMatchTableType(matchedTuv);
                    matchInfoMap.put("matchedTableType", matchedTableType);

                    matchedTuvMapForSpecifiedTrgLocale.add(matchInfoMap);
                }
                innerMap.put(targetLocale.getId(), matchedTuvMapForSpecifiedTrgLocale);

                trgLocaleMatchesMap.putAll(innerMap);
            }

            originalTuvId2MatchesMap.put(originalTuvId, trgLocaleMatchesMap);
        }
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
        throw new WebServiceException(e.getMessage());
    } finally {
        try {
            if (session != null) {
                session.close();
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new WebServiceException(e.getMessage());
        }
    }

    return originalTuvId2MatchesMap;
}