Example usage for java.util HashSet contains

List of usage examples for java.util HashSet contains

Introduction

In this page you can find the example usage for java.util HashSet contains.

Prototype

public boolean contains(Object o) 

Source Link

Document

Returns true if this set contains the specified element.

Usage

From source file:com.squid.kraken.v4.core.analysis.engine.project.DynamicManager.java

/**
 * dynamic relation loading: check all existing FK and automatically create
 * relation if not already concrete//from w  w w.  j  a va 2 s .c om
 * 
 * @param root
 * @param domains
 * @param coverage
 * @param concretes
 * @return
 */
private List<Relation> loadDynamicRelations(Universe root, List<Domain> domains, Map<Table, Domain> coverage,
        List<Relation> concretes) {
    Project project = root.getProject();
    HashSet<ExpressionAST> dedup = new HashSet<>();// dedup by expression
    HashSet<String> naturals = new HashSet<>();// dedup by ID for naturals
    List<Relation> relations = new ArrayList<Relation>();
    for (Relation concrete : concretes) {
        relations.add(concrete);
        naturals.add(concrete.getOid());
        // check for dedup
        if (concrete.getJoinExpression() != null) {
            try {
                ExpressionAST join = parseResilient(root, concrete, concretes);
                dedup.add(join);
            } catch (ScopeException e) {
                // ignore
            }
        }
    }
    for (Domain domain : domains) {
        try {
            if (!domain.getOptions().getReinjected() && !domain.getOptions().getAlink()) {
                Table table = root.getTable(domain);
                HashMap<String, NaturalRelation> dedupLinks = new HashMap<>();
                for (ForeignKey fk : getForeignKeys(table)) {
                    Table targetTable = fk.getPrimaryTable();
                    Domain target = coverage.get(targetTable);
                    if (target != null) {
                        // create a relation ?
                        String link = genRelationLinkId(project, domain, target);
                        String id = link + ":" + fk.getName();
                        String digest = digest(id);
                        Relation relation = null;
                        NaturalRelation samesame = null;
                        if (!naturals.contains(digest)) {
                            String leftName = domain.getName();
                            String rightName = target.getName();
                            samesame = dedupLinks.get(link);
                            if (samesame != null) {
                                leftName += "[" + fk.getName() + "]";
                                rightName += "[" + fk.getName() + "]";
                                if (samesame.first) {// it's the first
                                    samesame.rel.setLeftName(
                                            samesame.rel.getLeftName() + "[" + samesame.fk.getName() + "]");
                                    samesame.rel.setRightName(
                                            samesame.rel.getRightName() + "[" + samesame.fk.getName() + "]");
                                }
                            }
                            RelationPK relationPk = new RelationPK(project.getId(), digest);
                            relation = new Relation(relationPk, domain.getId(), Cardinality.MANY,
                                    target.getId(), Cardinality.ZERO_OR_ONE, leftName, rightName,
                                    new Expression("'" + fk.getName() + "'"), true);
                            AccessRightsUtils.getInstance().setAccessRights(root.getContext(), relation,
                                    project);
                            try {
                                ExpressionAST check = root.getParser().parse(relation);
                                if (!dedup.contains(check)) {
                                    relations.add(relation);
                                }
                            } catch (ScopeException e) {
                                // ignore if invalid
                            }
                        }
                        // always handle dedup
                        dedupLinks.put(link,
                                new NaturalRelation(relation, fk, relation != null && samesame == null));
                    }
                }
            } else {
                // Use linked source or origin sources.
                domain.getOptions().getLinkSource();
                // Table table = root.getTable(domain);
                // for (ForeignKey fk : getForeignKeys(table)) {
                // Table targetTable = fk.getPrimaryTable();
                // Domain target = coverage.get(targetTable);
                // if (target != null) {
                // // create a relation ?
                // String id = "rel/" + domain.getId().toUUID() + "-" +
                // target.getId().toUUID() + ":" + fk.getName();
                // RelationPK relationPk = new RelationPK(project.getId(),
                // digest(id));
                // Relation relation =
                // new Relation(relationPk,
                // domain.getId(),
                // Cardinality.MANY,
                // target.getId(),
                // Cardinality.ZERO_OR_ONE,
                // domain.getName(),
                // target.getName(),
                // new Expression("'" + fk.getName() + "'"), true);
                // relation.setAccessRights(accessRights);
                // try {
                // ExpressionAST check = root.getParser().parse(relation);
                // if (!dedup.contains(check)) {
                // relations.add(relation);
                // }
                // } catch (ScopeException e) {
                // // ignore if invalid
                // }
                // }
                // }

            }
        } catch (ScopeException e) {
            logger.info(e.getMessage(), e);
        }
    }
    //
    return relations;
}

From source file:com.gargoylesoftware.htmlunit.WebClient.java

/**
 * <span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span><br>
 *
 * Loads downloaded responses into the corresponding windows.
 * TODO: refactor it before next release.
 * @throws IOException in case of exception
 * @throws FailingHttpStatusCodeException in case of exception
 *//*from w  w  w .  j  av  a  2  s. c  om*/
public void loadDownloadedResponses() throws FailingHttpStatusCodeException, IOException {
    final List<LoadJob> queue;

    // synchronize access to the loadQueue_,
    // to be sure no job is ignored
    synchronized (loadQueue_) {
        if (loadQueue_.isEmpty()) {
            return;
        }
        queue = new ArrayList<>(loadQueue_);
        loadQueue_.clear();
    }

    final HashSet<WebWindow> updatedWindows = new HashSet<>();
    for (int i = queue.size() - 1; i >= 0; --i) {
        final LoadJob downloadedResponse = queue.get(i);
        if (downloadedResponse.isOutdated()) {
            LOG.info("No usage of download: " + downloadedResponse);
            continue;
        }
        final WebWindow window = resolveWindow(downloadedResponse.requestingWindow_,
                downloadedResponse.target_);
        if (!updatedWindows.contains(window)) {
            final WebWindow win = openTargetWindow(downloadedResponse.requestingWindow_,
                    downloadedResponse.target_, "_self");
            if (downloadedResponse.urlWithOnlyHashChange_ != null) {
                final HtmlPage page = (HtmlPage) downloadedResponse.requestingWindow_.getEnclosedPage();
                final String oldURL = page.getUrl().toExternalForm();
                page.getWebResponse().getWebRequest().setUrl(downloadedResponse.urlWithOnlyHashChange_);
                page.getWebResponse().getWebRequest()
                        .setCloneForHistoryAPI(downloadedResponse.request_.isCloneForHistoryAPI());
                page.getWebResponse().getWebRequest().setState(downloadedResponse.request_.getState());
                win.getHistory().addPage(page);

                // update location.hash
                final Window jsWindow = (Window) win.getScriptableObject();
                if (null != jsWindow) {
                    final Location location = jsWindow.getLocation();
                    location.setHash(oldURL, downloadedResponse.urlWithOnlyHashChange_.getRef());
                }
            } else {
                final Page pageBeforeLoad = win.getEnclosedPage();
                loadWebResponseInto(downloadedResponse.response_, win);

                // start execution here.
                if (scriptEngine_ != null) {
                    scriptEngine_.registerWindowAndMaybeStartEventLoop(win);
                }

                if (pageBeforeLoad != win.getEnclosedPage()) {
                    updatedWindows.add(win);
                }

                // check and report problems if needed
                throwFailingHttpStatusCodeExceptionIfNecessary(downloadedResponse.response_);
            }
        } else {
            LOG.info("No usage of download: " + downloadedResponse);
        }
    }
}

From source file:com.uwsoft.editor.data.manager.DataManager.java

private void checkForConsistancy() {
    // check if current project requires cleanup
    // Cleanup unused meshes
    // 1. open all scenes make list of mesh_id's and then remove all unused meshes
    HashSet<String> uniqueMeshIds = new HashSet<String>();
    FileHandle sourceDir = new FileHandle(currentWorkingPath + "/" + currentProjectVO.projectName + "/scenes/");
    for (FileHandle entry : sourceDir.list(new DTFilenameFilter())) {
        if (!entry.file().isDirectory()) {
            Json json = new Json();
            SceneVO sceneVO = json.fromJson(SceneVO.class, entry);
            if (sceneVO.composite == null)
                continue;
            ArrayList<MainItemVO> items = sceneVO.composite.getAllItems();
            for (MainItemVO vo : items) {
                if (vo.meshId.equals("-1"))
                    continue;
                uniqueMeshIds.add(vo.meshId);
            }/*from  www .java 2  s .  c o  m*/
            for (CompositeItemVO libraryItem : sceneVO.libraryItems.values()) {
                if (libraryItem.composite == null)
                    continue;
                items = libraryItem.composite.getAllItems();
                for (MainItemVO vo : items) {
                    if (vo.meshId.equals("-1"))
                        continue;
                    uniqueMeshIds.add(vo.meshId);
                }
            }
        }
    }
    // addsset list
    for (String meshId : currentProjectInfoVO.assetMeshMap.values()) {
        uniqueMeshIds.add(meshId);
    }

    // check for not used meshes and remove
    Iterator<Map.Entry<String, MeshVO>> iter = currentProjectInfoVO.meshes.entrySet().iterator();
    while (iter.hasNext()) {
        Map.Entry<String, MeshVO> entry = iter.next();
        if (!uniqueMeshIds.contains(entry.getKey())) {
            System.out.println("KEY " + entry.getKey());
            iter.remove();
            System.out.println("meshe removed");
        }
    }
}

From source file:com.sonicle.webtop.core.app.WebTopManager.java

private OGroup doGroupInsert(Connection con, String domainId, GroupEntity group)
        throws DAOException, WTException {
    GroupDAO dao = GroupDAO.getInstance();

    // Insert Group record
    logger.debug("Inserting group... [{}]", group.getGroupId());
    OGroup ogroup = new OGroup();
    ogroup.setDomainId(domainId);/*from ww  w .  j  a  va  2 s  .c om*/
    ogroup.setGroupId(group.getGroupId());
    ogroup.setEnabled(true);
    ogroup.setGroupUid(IdentifierUtils.getUUID());
    ogroup.setDisplayName(group.getDisplayName());
    ogroup.setSecret(null);
    dao.insert(con, ogroup);

    logger.debug("Inserting users associations...");
    HashSet<String> usedUserUids = new HashSet<>();
    for (AssignedUser assiUser : group.getAssignedUsers()) {
        final String userUid = userToUid(new UserProfileId(group.getDomainId(), assiUser.getUserId()));
        if (!usedUserUids.contains(userUid)) { // Avoid userUid duplicates
            doInsertUserAssociation(con, userUid, ogroup.getGroupUid());
            usedUserUids.add(userUid);
        }
    }

    logger.debug("Inserting roles associations");
    HashSet<String> usedRoleUids = new HashSet<>();
    for (AssignedRole assiRole : group.getAssignedRoles()) {
        final String roleUid = assiRole.getRoleUid();
        if (!usedRoleUids.contains(roleUid)) { // Avoid roles duplicates
            doInsertRoleAssociation(con, ogroup.getGroupUid(), roleUid);
            usedRoleUids.add(roleUid);
        }
    }

    // Insert permissions
    logger.debug("Inserting permissions");
    for (ORolePermission perm : group.getPermissions()) {
        doInsertPermission(con, ogroup.getGroupUid(), perm.getServiceId(), perm.getKey(), perm.getAction(),
                "*");
    }
    for (ORolePermission perm : group.getServicesPermissions()) {
        doInsertPermission(con, ogroup.getGroupUid(), CoreManifest.ID, "SERVICE",
                ServicePermission.ACTION_ACCESS, perm.getInstance());
    }

    return ogroup;
}

From source file:edu.ucla.cs.scai.canali.core.index.utils.DBpediaOntologyUtils.java

public void createEntityClassesFile(HashSet<String> acceptableEntities, HashSet<String> acceptableClasses)
        throws Exception {
    System.out.println("Saving entity classes");
    try (PrintWriter out = new PrintWriter(new FileOutputStream(destinationPath + "entity_classes", false),
            true);//from  w  w  w  . ja v a2 s  .  c  o  m
            BufferedReader in1 = new BufferedReader(
                    new FileReader(downloadedFilesPath + "instance_types_en.nt"));
            BufferedReader in2 = new BufferedReader(
                    new FileReader(downloadedFilesPath + "instance_types_heuristic_en.nt"))) {
        String regex = "<(.*)> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <(.*)>";
        Pattern p = Pattern.compile(regex);
        String l = in1.readLine();
        while (l != null) {
            Matcher m = p.matcher(l);
            if (m.find()) {
                String eUri = m.group(1);
                String cUri = m.group(2);
                if (acceptableEntities.contains(eUri) && acceptableClasses.contains(cUri)) {
                    out.println(eUri + "\t" + cUri);
                }
            }
            l = in1.readLine();
        }
        l = in2.readLine();
        while (l != null) {
            Matcher m = p.matcher(l);
            if (m.find()) {
                String eUri = m.group(1);
                String cUri = m.group(2);
                if (acceptableEntities.contains(eUri) && acceptableClasses.contains(cUri)) {
                    out.println(eUri + "\t" + cUri);
                }
            }
            l = in2.readLine();
        }
    }
}

From source file:com.sonicle.webtop.core.app.WebTopManager.java

private OUser doUserInsert(Connection con, ODomain domain, UserEntity user) throws DAOException, WTException {
    UserDAO udao = UserDAO.getInstance();
    UserInfoDAO uidao = UserInfoDAO.getInstance();

    InternetAddress email = InternetAddressUtils.toInternetAddress(user.getUserId(), domain.getInternetName(),
            null);/*  w w w  . j  a  v  a  2 s .co  m*/
    if (email == null)
        throw new WTException("Cannot create a valid email address [{0}, {1}]", user.getUserId(),
                domain.getInternetName());

    // Insert User record
    logger.debug("Inserting user");
    OUser ouser = new OUser();
    ouser.setDomainId(domain.getDomainId());
    ouser.setUserId(user.getUserId());
    ouser.setEnabled(user.getEnabled());
    ouser.setUserUid(IdentifierUtils.getUUID());
    ouser.setDisplayName(user.getDisplayName());
    ouser.setSecret(generateSecretKey());
    udao.insert(con, ouser);

    // Insert UserInfo record
    logger.debug("Inserting userInfo");
    OUserInfo oui = new OUserInfo();
    oui.setDomainId(domain.getDomainId());
    oui.setUserId(user.getUserId());
    oui.setFirstName(user.getFirstName());
    oui.setLastName(user.getLastName());
    oui.setEmail(email.getAddress());
    uidao.insert(con, oui);

    logger.debug("Inserting groups associations");
    HashSet<String> usedGroupUids = new HashSet<>();
    for (AssignedGroup assiGroup : user.getAssignedGroups()) {
        final String groupUid = groupToUid(new UserProfileId(user.getDomainId(), assiGroup.getGroupId()));
        if (!usedGroupUids.contains(groupUid)) {
            // Due to built-in assigned groups, collection of assigned
            // groups can contain duplicates; so skip them.
            doInsertUserAssociation(con, ouser.getUserUid(), groupUid);
            usedGroupUids.add(groupUid);
        }
    }

    logger.debug("Inserting roles associations");
    HashSet<String> usedRoleUids = new HashSet<>();
    for (AssignedRole assiRole : user.getAssignedRoles()) {
        final String roleUid = assiRole.getRoleUid();
        if (!usedRoleUids.contains(roleUid)) {
            // Due to built-in assigned roles, collection of assigned
            // roles can contain duplicates; so skip them.
            doInsertRoleAssociation(con, ouser.getUserUid(), roleUid);
            usedRoleUids.add(roleUid);
        }
    }

    // Insert permissions
    logger.debug("Inserting permissions");
    for (ORolePermission perm : user.getPermissions()) {
        doInsertPermission(con, ouser.getUserUid(), perm.getServiceId(), perm.getKey(), perm.getAction(), "*");
    }
    for (ORolePermission perm : user.getServicesPermissions()) {
        doInsertPermission(con, ouser.getUserUid(), CoreManifest.ID, "SERVICE", ServicePermission.ACTION_ACCESS,
                perm.getInstance());
    }

    return ouser;
}

From source file:gov.nih.nci.evs.browser.utils.MetaTreeUtils.java

public int getSubconceptCountExt(String scheme, String version, String CUI, String sab, String asso_name,
        boolean direction) {
    List<String> par_chd_assoc_list = new ArrayList();
    par_chd_assoc_list.add(asso_name);// w  w w  .  ja v a 2s  .  c o  m

    Map<String, List<BySourceTabResults>> map = null;

    LexBIGService lbs = RemoteServerUtil.createLexBIGService();
    MetaBrowserService mbs = null;
    try {
        mbs = (MetaBrowserService) lbs.getGenericExtension("metabrowser-extension");
        if (direction) {
            map = mbs.getBySourceTabDisplay(CUI, sab, par_chd_assoc_list, Direction.SOURCEOF);
        } else {
            map = mbs.getBySourceTabDisplay(CUI, sab, par_chd_assoc_list, Direction.TARGETOF);
        }
    } catch (Exception ex) {
        ex.printStackTrace();
        return -1;
    }
    int knt = 0;
    HashSet hset = new HashSet();

    Iterator it = map.entrySet().iterator();
    while (it.hasNext()) {
        Entry thisEntry = (Entry) it.next();
        String rel = (String) thisEntry.getKey();
        List<BySourceTabResults> relations = (List<BySourceTabResults>) thisEntry.getValue();

        //for (String rel : map.keySet()) {
        //List<BySourceTabResults> relations = map.get(rel);

        for (BySourceTabResults result : relations) {
            String code = result.getCui();
            if (code.compareTo(CUI) != 0 && !hset.contains(code)) {
                hset.add(code);
            }
            String name = result.getTerm();
            // _logger.debug("(***) subconcept: " + name + " " + code);
            knt++;
        }
    }
    return hset.size();
}

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/* www  . java  2 s.  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.smartbear.collaborator.issue.IssueRest.java

/**
 * Downloads raw files from Fisheye, calculates checksum for each file and
 * puts them to zip file//from  w  w  w  .j  a  v  a  2  s  .  co  m
 * 
 * @param changesetList 
 * @return
 * @throws Exception
 */
private java.io.File downloadRawFilesFromFisheye(List<Changeset> changesetList) throws Exception {
    // Create temp zip file where versions will be put
    java.io.File targetZipFile = java.io.File.createTempFile("store-", ".zip");
    String urlGetRawFileContent = null;
    byte[] fileBytes = null;
    try {

        FileOutputStream fileOutputStream = new FileOutputStream(targetZipFile);
        ZipOutputStream zipOutputStream = new ZipOutputStream(fileOutputStream);
        HashSet<String> zipEntryNames = new HashSet<String>();

        Client client;
        WebResource service;
        ClientResponse response;
        InputStream fileInputStream;

        ZipEntry zipEntry;
        Action action;

        // Go through repositories->commits->files to put versions in temp
        // zip file
        for (Changeset changeset : changesetList) {

            for (File file : changeset.getFiles()) {

                // Get raw file content from Fisheye server
                // Example
                // http://nb-kpl:8060/browse/~raw,r=HEAD/svn_test/test/log.txt

                action = Util.getVersionAction(file.getChangeType());
                if (action == null) {
                    continue;
                }

                if (action == Action.DELETED) {
                    fileBytes = new byte[0];
                } else {
                    urlGetRawFileContent = Util.encodeURL(configModel.getFisheyeUrl() + file.getContentLink());
                    response = getFisheyeClientResponse(urlGetRawFileContent, configModel, false);

                    fileInputStream = response.getEntity(InputStream.class);
                    fileBytes = IOUtils.toByteArray(fileInputStream);

                    LOGGER.debug("Request to Fisheye: " + urlGetRawFileContent);
                    LOGGER.debug("Response from Fisheye" + new String(fileBytes));

                    //Check that we really received file content
                    checkRawFileResponse(response);
                }
                // Set calculated md5 for raw version
                file.setMd5(calculateMd5(fileBytes));

                if (!zipEntryNames.contains(file.getMd5())) {
                    zipEntry = new ZipEntry(file.getMd5());
                    zipOutputStream.putNextEntry(zipEntry);

                    // write version to temp zip file
                    zipOutputStream.write(fileBytes);

                    zipEntryNames.add(file.getMd5());
                }

                // Check if file was modified/deleted then download also
                // previous version
                if (action == Action.MODIFIED || action == Action.DELETED) {

                    if (!Util.isEmpty(file.getAncestor())) {

                        ClientResponse ancestorChangesetResp = getFisheyeClientResponse(
                                Util.encodeURL(configModel.getFisheyeUrl() + FISHEYE_CHANGESET_API
                                        + changeset.getRepositoryName() + "/" + file.getAncestor()),
                                configModel, true);
                        String ancestorChangesetRespString = ancestorChangesetResp.getEntity(String.class);
                        ObjectNode ancestorChangesetNode = (ObjectNode) mapper
                                .readTree(ancestorChangesetRespString);
                        file.setPreviousCommitAuthor(ancestorChangesetNode.get("author").asText());
                        file.setPreviousCommitDate(new Date(ancestorChangesetNode.get("date").asLong()));
                        file.setPreviousCommitComment(ancestorChangesetNode.get("comment").asText());

                        urlGetRawFileContent = Util
                                .encodeURL(configModel.getFisheyeUrl() + "/browse/~raw,r=" + file.getAncestor()
                                        + "/" + changeset.getRepositoryName() + "/" + file.getPath());
                        response = getFisheyeClientResponse(urlGetRawFileContent, configModel, false);

                        fileInputStream = response.getEntity(InputStream.class);
                        fileBytes = IOUtils.toByteArray(fileInputStream);

                        LOGGER.debug("Request to Fisheye: " + urlGetRawFileContent);
                        LOGGER.debug("Response from Fisheye" + new String(fileBytes));

                        //Check that we really received file content
                        checkRawFileResponse(response);

                        // Set calculated md5 for raw version
                        file.setPreviousMd5(calculateMd5(fileBytes));

                        if (!zipEntryNames.contains(file.getPreviousMd5())) {
                            zipEntry = new ZipEntry(file.getPreviousMd5());
                            zipOutputStream.putNextEntry(zipEntry);

                            // write version to temp zip file
                            zipOutputStream.write(fileBytes);

                            zipEntryNames.add(file.getPreviousMd5());
                        }

                    } else {
                        String errorMsg = "Please, try to \"Create/Update Review\" a little bit later. FishEye server hasn't been refreshed commit info yet.";
                        LOGGER.error(errorMsg);
                        throw new Exception(errorMsg);
                    }
                }
            }
        }

        // close ZipEntry to store the stream to the file
        zipOutputStream.closeEntry();
        zipOutputStream.close();
        fileOutputStream.close();
        return targetZipFile;

    } catch (Exception e) {
        LOGGER.error("Request URL to Fisheye: " + urlGetRawFileContent, e);
        LOGGER.error("Response from Fisheye: " + (fileBytes != null ? new String(fileBytes) : ""), e);
        throw new Exception(
                "Can't download raw versions from FishEye server. Check that FishEye server is running. \n "
                        + "Request URL to Fisheye: " + urlGetRawFileContent + "\n" + e.getMessage());
    }

}

From source file:com.nortal.jroad.typegen.xmlbeans.XteeSchemaCodePrinter.java

void printStringEnumeration(SchemaType sType) throws IOException {
    SchemaType baseEnumType = sType.getBaseEnumType();
    String baseEnumClass = baseEnumType.getFullJavaName();
    boolean hasBase;
    if (baseEnumType.isAnonymousType() && baseEnumType.isSkippedAnonymousType()) {
        if (sType.getContentBasedOnType() != null)
            hasBase = sType.getContentBasedOnType().getBaseType() != baseEnumType;
        else/*from   w ww  .  j  av  a2 s .com*/
            hasBase = sType.getBaseType() != baseEnumType;
    } else
        hasBase = baseEnumType != sType;

    if (!hasBase) {
        emit("");
        emit("org.apache.xmlbeans.StringEnumAbstractBase enumValue();");
        emit("void set(org.apache.xmlbeans.StringEnumAbstractBase e);");
    }

    emit("");
    SchemaStringEnumEntry[] entries = sType.getStringEnumEntries();
    HashSet<String> seenValues = new HashSet<String>();
    HashSet<String> repeatValues = new HashSet<String>();
    for (int i = 0; i < entries.length; i++) {
        String enumValue = entries[i].getString();
        if (seenValues.contains(enumValue)) {
            repeatValues.add(enumValue);
            continue;
        } else
            seenValues.add(enumValue);
        String constName = entries[i].getEnumName();
        if (hasBase)
            emit("static final " + baseEnumClass + ".Enum " + constName + " = " + baseEnumClass + "."
                    + constName + ";");
        else
            emit("static final Enum " + constName + " = Enum.forString(\"" + javaStringEscape(enumValue)
                    + "\");");
    }
    emit("");
    for (int i = 0; i < entries.length; i++) {
        if (repeatValues.contains(entries[i].getString()))
            continue;
        String constName = "INT_" + entries[i].getEnumName();
        if (hasBase)
            emit("static final int " + constName + " = " + baseEnumClass + "." + constName + ";");
        else
            emit("static final int " + constName + " = Enum." + constName + ";");
    }
    if (!hasBase) {
        emit("");
        emit("/**");
        emit(" * Enumeration value class for " + baseEnumClass + ".");
        emit(" * These enum values can be used as follows:");
        emit(" * <pre>");
        emit(" * enum.toString(); // returns the string value of the enum");
        emit(" * enum.intValue(); // returns an int value, useful for switches");
        if (entries.length > 0)
            emit(" * // e.g., case Enum.INT_" + entries[0].getEnumName());
        emit(" * Enum.forString(s); // returns the enum value for a string");
        emit(" * Enum.forInt(i); // returns the enum value for an int");
        emit(" * </pre>");
        emit(" * Enumeration objects are immutable singleton objects that");
        emit(" * can be compared using == object equality. They have no");
        emit(" * public constructor. See the constants defined within this");
        emit(" * class for all the valid values.");
        emit(" */");
        emit("static final class Enum extends org.apache.xmlbeans.StringEnumAbstractBase");
        emit("{");
        indent();
        emit("/**");
        emit(" * Returns the enum value for a string, or null if none.");
        emit(" */");
        emit("public static Enum forString(java.lang.String s)");
        emit("    { return (Enum)table.forString(s); }");
        emit("/**");
        emit(" * Returns the enum value corresponding to an int, or null if none.");
        emit(" */");
        emit("public static Enum forInt(int i)");
        emit("    { return (Enum)table.forInt(i); }");
        emit("");
        emit("private Enum(java.lang.String s, int i)");
        emit("    { super(s, i); }");
        emit("");
        for (int i = 0; i < entries.length; i++) {
            String constName = "INT_" + entries[i].getEnumName();
            int intValue = entries[i].getIntValue();
            emit("static final int " + constName + " = " + intValue + ";");
        }
        emit("");
        emit("public static final org.apache.xmlbeans.StringEnumAbstractBase.Table table =");
        emit("    new org.apache.xmlbeans.StringEnumAbstractBase.Table");
        emit("(");
        indent();
        emit("new Enum[]");
        emit("{");
        indent();
        for (int i = 0; i < entries.length; i++) {
            String enumValue = entries[i].getString();
            String constName = "INT_" + entries[i].getEnumName();
            emit("new Enum(\"" + javaStringEscape(enumValue) + "\", " + constName + "),");
        }
        outdent();
        emit("}");
        outdent();
        emit(");");
        emit("private static final long serialVersionUID = 1L;");
        emit("private java.lang.Object readResolve() { return forInt(intValue()); } ");
        outdent();
        emit("}");
    }
}