Example usage for java.util Set retainAll

List of usage examples for java.util Set retainAll

Introduction

In this page you can find the example usage for java.util Set retainAll.

Prototype

boolean retainAll(Collection<?> c);

Source Link

Document

Retains only the elements in this set that are contained in the specified collection (optional operation).

Usage

From source file:org.slc.sli.api.resources.generic.service.DefaultResourceService.java

@SuppressWarnings("unchecked")
private ServiceResponse getAssociatedEntities(final Resource base, final Resource association, final String id,
        final Resource resource, final String associationKey, final URI requestUri) {
    List<String> valueList = Arrays.asList(id.split(","));
    final List<String> filteredIdList = new ArrayList<String>();

    final EntityDefinition finalEntity = resourceHelper.getEntityDefinition(resource);
    final EntityDefinition assocEntity = resourceHelper.getEntityDefinition(association);
    final EntityDefinition baseEntity = resourceHelper.getEntityDefinition(base);

    String resourceKey = getConnectionKey(association, resource);
    String key = "_id";

    try {/*from  w w  w  . j  a v a  2 s.c  o m*/
        final ApiQuery apiQuery = resourceServiceHelper.getApiQuery(assocEntity);

        addGranularAccessCriteria(assocEntity, apiQuery);

        apiQuery.setLimit(0);
        apiQuery.addCriteria(new NeutralCriteria(associationKey, "in", valueList));
        if (association.getResourceType().equals(ResourceNames.STUDENT_SCHOOL_ASSOCIATIONS) && requestUri
                .getPath().matches("^/api/rest/[^/]+/schools/[^/]+/studentSchoolAssociations/students")) {
            apiQuery.addOrQuery(new NeutralQuery(new NeutralCriteria(ParameterConstants.EXIT_WITHDRAW_DATE,
                    NeutralCriteria.CRITERIA_EXISTS, false)));
            apiQuery.addOrQuery(new NeutralQuery(
                    new NeutralCriteria(ParameterConstants.EXIT_WITHDRAW_DATE, NeutralCriteria.CRITERIA_GTE,
                            DateTime.now().toString(DateTimeFormat.forPattern("yyyy-MM-dd")))));
        }

        Iterable<EntityBody> entityList;
        if (SecurityUtil.isStaffUser()) {
            entityList = assocEntity.getService().listBasedOnContextualRoles(apiQuery);
        } else {
            entityList = assocEntity.getService().list(apiQuery);
        }

        for (EntityBody entityBody : entityList) {
            List<String> filteredIds = entityBody.getValues(resourceKey);
            if ((filteredIds == null) || (filteredIds.isEmpty())) {
                key = resourceKey;
                if (associationKey.equals("_id")) {
                    filteredIdList.addAll(valueList);
                    break;

                } else {
                    resourceKey = "id";
                    filteredIds = entityBody.getValues(resourceKey);
                }
            }
            filteredIdList.addAll(filteredIds);
        }

        List<EntityBody> entityBodyList;
        final ApiQuery finalApiQuery = resourceServiceHelper.getApiQuery(finalEntity, requestUri);

        addGranularAccessCriteria(finalEntity, finalApiQuery);

        //skip this when someone is querying on public entities
        if (!(EntityNames.isPublic(finalEntity.getType()) && finalApiQuery.getCriteria().size() > 1)) {

            //Mongo blows up if we have multiple $in or equal criteria for the same key.
            //To avoid that case, if we do have duplicate keys, set the value for that
            //criteria to the intersection of the two critiera values
            boolean skipIn = false;
            for (NeutralCriteria crit : finalApiQuery.getCriteria()) {
                if (crit.getKey().equals(key) && (crit.getOperator().equals(NeutralCriteria.CRITERIA_IN)
                        || crit.getOperator().equals(NeutralCriteria.OPERATOR_EQUAL))) {
                    skipIn = true;
                    Set<Object> valueSet = new HashSet<Object>();
                    if (crit.getValue() instanceof Collection) {
                        valueSet.addAll((Collection<Object>) crit.getValue());
                    } else {
                        valueSet.add(crit.getValue());
                    }
                    valueSet.retainAll(filteredIdList);
                    crit.setValue(valueSet);
                }
            }

            if (!skipIn) {
                finalApiQuery.addCriteria(new NeutralCriteria(key, "in", filteredIdList));
            }

        }

        // if we're only getting the count of this query, just create an empty list, otherwise
        // execute the query to get the bodies - DS-1046, providing an API for retrieving counts only.
        if (finalApiQuery.isCountOnly()) {
            entityBodyList = new ArrayList<EntityBody>();
        } else {
            entityBodyList = (List<EntityBody>) getEntityBodies(finalApiQuery, finalEntity,
                    finalEntity.getResourceName());
        }

        long count = getEntityCount(finalEntity, finalApiQuery);

        return new ServiceResponse(adapter.migrate(entityBodyList, finalEntity.getResourceName(), GET), count);
    } catch (NoGranularAccessDatesException e) {
        List<EntityBody> entityBodyList = Collections.emptyList();
        return new ServiceResponse(entityBodyList, 0);
    }
}

From source file:org.lockss.exporter.kbart.KbartExportFilter.java

/**
 * Get the set of fields from the filter's field ordering which were omitted 
 * due to being empty.//from  w w w  . j a va2s.  c  o  m
 * @return the set of empty fields which were omitted from the ordering
 */
public Set<Field> getOmittedEmptyFields() {
    Set<Field> empties = EnumSet.copyOf(columnOrdering.getFields());
    empties.retainAll(emptyFields);
    return empties;
}

From source file:beast.evolution.tree.RandomTree.java

@SuppressWarnings("unchecked")
@Override/*from   w w  w . ja  va 2 s  .co  m*/
public void initStateNodes() {
    // find taxon sets we are dealing with
    taxonSets = new ArrayList<>();
    m_bounds = new ArrayList<>();
    distributions = new ArrayList<>();
    taxonSetIDs = new ArrayList<>();
    lastMonophyletic = 0;

    if (taxaInput.get() != null) {
        taxa.addAll(taxaInput.get().getTaxaNames());
    } else {
        taxa.addAll(m_taxonset.get().asStringList());
    }

    // pick up constraints from outputs, m_inititial input tree and output tree, if any
    List<MRCAPrior> calibrations = new ArrayList<>();
    calibrations.addAll(calibrationsInput.get());
    //       for (BEASTObject beastObject : outputs) {
    //       // pick up constraints in outputs
    //      if (beastObject instanceof MRCAPrior && !calibrations.contains(beastObject)) {
    //         calibrations.add((MRCAPrior) beastObject);
    //      } else  if (beastObject instanceof Tree) {
    //           // pick up constraints in outputs if output tree
    //         Tree tree = (Tree) beastObject;
    //         if (tree.m_initial.get() == this) {
    //               for (BEASTObject beastObject2 : tree.outputs) {
    //                  if (beastObject2 instanceof MRCAPrior && !calibrations.contains(beastObject2)) {
    //                     calibrations.add((MRCAPrior) beastObject2);
    //                  }                      
    //               }
    //         }
    //      }
    //      
    //   }
    // pick up constraints in m_initial tree
    for (final Object beastObject : getOutputs()) {
        if (beastObject instanceof MRCAPrior && !calibrations.contains(beastObject)) {
            calibrations.add((MRCAPrior) beastObject);
        }
    }
    if (m_initial.get() != null) {
        for (final Object beastObject : m_initial.get().getOutputs()) {
            if (beastObject instanceof MRCAPrior && !calibrations.contains(beastObject)) {
                calibrations.add((MRCAPrior) beastObject);
            }
        }
    }

    for (final MRCAPrior prior : calibrations) {
        final TaxonSet taxonSet = prior.taxonsetInput.get();
        if (taxonSet != null && !prior.onlyUseTipsInput.get()) {
            final Set<String> usedTaxa = new LinkedHashSet<>();
            if (taxonSet.asStringList() == null) {
                taxonSet.initAndValidate();
            }
            for (final String taxonID : taxonSet.asStringList()) {
                if (!taxa.contains(taxonID)) {
                    throw new IllegalArgumentException("Taxon <" + taxonID
                            + "> could not be found in list of taxa. Choose one of " + taxa);
                }
                usedTaxa.add(taxonID);
            }
            final ParametricDistribution distr = prior.distInput.get();
            final Bound bounds = new Bound();
            if (distr != null) {
                List<BEASTInterface> beastObjects = new ArrayList<>();
                distr.getPredecessors(beastObjects);
                for (int i = beastObjects.size() - 1; i >= 0; i--) {
                    beastObjects.get(i).initAndValidate();
                }
                try {
                    bounds.lower = distr.inverseCumulativeProbability(0.0) + distr.offsetInput.get();
                    bounds.upper = distr.inverseCumulativeProbability(1.0) + distr.offsetInput.get();
                } catch (MathException e) {
                    Log.warning.println("At RandomTree::initStateNodes, bound on MRCAPrior could not be set "
                            + e.getMessage());
                }
            }

            if (prior.isMonophyleticInput.get()) {
                // add any monophyletic constraint
                taxonSets.add(lastMonophyletic, usedTaxa);
                distributions.add(lastMonophyletic, distr);
                m_bounds.add(lastMonophyletic, bounds);
                taxonSetIDs.add(prior.getID());
                lastMonophyletic++;
            } else {
                // only calibrations with finite bounds are added
                if (!Double.isInfinite(bounds.lower) || !Double.isInfinite(bounds.upper)) {
                    taxonSets.add(usedTaxa);
                    distributions.add(distr);
                    m_bounds.add(bounds);
                    taxonSetIDs.add(prior.getID());
                }
            }
        }
    }

    // assume all calibration constraints are MonoPhyletic
    // TODO: verify that this is a reasonable assumption
    lastMonophyletic = taxonSets.size();

    // sort constraints such that if taxon set i is subset of taxon set j, then i < j
    for (int i = 0; i < lastMonophyletic; i++) {
        for (int j = i + 1; j < lastMonophyletic; j++) {

            Set<String> intersection = new LinkedHashSet<>(taxonSets.get(i));
            intersection.retainAll(taxonSets.get(j));

            if (intersection.size() > 0) {
                final boolean isSubset = taxonSets.get(i).containsAll(taxonSets.get(j));
                final boolean isSubset2 = taxonSets.get(j).containsAll(taxonSets.get(i));
                // sanity check: make sure either
                // o taxonset1 is subset of taxonset2 OR
                // o taxonset1 is superset of taxonset2 OR
                // o taxonset1 does not intersect taxonset2
                if (!(isSubset || isSubset2)) {
                    throw new IllegalArgumentException(
                            "333: Don't know how to generate a Random Tree for taxon sets that intersect, "
                                    + "but are not inclusive. Taxonset " + taxonSetIDs.get(i) + " and "
                                    + taxonSetIDs.get(j));
                }
                // swap i & j if b1 subset of b2
                if (isSubset) {
                    swap(taxonSets, i, j);
                    swap(distributions, i, j);
                    swap(m_bounds, i, j);
                    swap(taxonSetIDs, i, j);
                }
            }
        }
    }

    // build tree of mono constraints such that j is parent of i if i is a subset of j but i+1,i+2,...,j-1 are not.
    // The last one, standing for the virtual "root" of all monophyletic clades is not associated with an actual clade
    final int[] parent = new int[lastMonophyletic];
    children = new List[lastMonophyletic + 1];
    for (int i = 0; i < lastMonophyletic + 1; i++) {
        children[i] = new ArrayList<>();
    }
    for (int i = 0; i < lastMonophyletic; i++) {
        int j = i + 1;
        while (j < lastMonophyletic && !taxonSets.get(j).containsAll(taxonSets.get(i))) {
            j++;
        }
        parent[i] = j;
        children[j].add(i);
    }

    // make sure upper bounds of a child does not exceed the upper bound of its parent
    for (int i = lastMonophyletic - 1; i >= 0; --i) {
        if (parent[i] < lastMonophyletic) {
            if (m_bounds.get(i).upper > m_bounds.get(parent[i]).upper) {
                m_bounds.get(i).upper = m_bounds.get(parent[i]).upper - 1e-100;
            }
        }
    }

    final PopulationFunction popFunction = populationFunctionInput.get();

    simulateTree(taxa, popFunction);
    if (rootHeightInput.get() != null) {
        scaleToFit(rootHeightInput.get() / root.getHeight(), root);
    }

    nodeCount = 2 * taxa.size() - 1;
    internalNodeCount = taxa.size() - 1;
    leafNodeCount = taxa.size();

    HashMap<String, Integer> taxonToNR = null;
    // preserve node numbers where possible
    if (m_initial.get() != null) {
        if (leafNodeCount == m_initial.get().getLeafNodeCount()) {
            // dont ask me how the initial tree is rubbish  (i.e. 0:0.0)
            taxonToNR = new HashMap<>();
            for (Node n : m_initial.get().getExternalNodes()) {
                taxonToNR.put(n.getID(), n.getNr());
            }
        }
    } else {
        taxonToNR = new HashMap<>();
        String[] taxa = getTaxaNames();
        for (int k = 0; k < taxa.length; ++k) {
            taxonToNR.put(taxa[k], k);
        }
    }
    // multiple simulation tries may produce an excess of nodes with invalid nr's. reset those.
    setNodesNrs(root, 0, new int[1], taxonToNR);

    initArrays();

    if (m_initial.get() != null) {
        m_initial.get().assignFromWithoutID(this);
    }
    for (int k = 0; k < lastMonophyletic; ++k) {
        final MRCAPrior p = calibrations.get(k);
        if (p.isMonophyleticInput.get()) {
            final TaxonSet taxonSet = p.taxonsetInput.get();
            if (taxonSet == null) {
                throw new IllegalArgumentException("Something is wrong with constraint " + p.getID()
                        + " -- a taxonset must be specified if a monophyletic constraint is enforced.");
            }
            final Set<String> usedTaxa = new LinkedHashSet<>();
            if (taxonSet.asStringList() == null) {
                taxonSet.initAndValidate();
            }
            usedTaxa.addAll(taxonSet.asStringList());
            /* int c = */ traverse(root, usedTaxa, taxonSet.getTaxonCount(), new int[1]);
            // boolean b = c == nrOfTaxa + 127;
        }
    }
}

From source file:org.scilla.converter.ExternalConverter.java

public boolean canConvert(Request req) {
    Set conv = new HashSet();
    Collection c;/*from ww  w. ja va 2  s.c  om*/
    Iterator it;

    // can handle input?
    c = (Collection) inputTypeMap.get(req.getInputType());
    if (c == null) {
        return false;
    }
    conv.addAll(c);
    // TODO remove all references to blacklisted converters at setup
    conv.removeAll(blacklistSet);
    if (conv.size() == 0) {
        return false;
    }

    // can handle output?
    c = (Collection) outputTypeMap.get(req.getOutputType());
    if (c == null) {
        return false;
    }
    conv.retainAll(c);
    if (conv.size() == 0) {
        return false;
    }

    // supports all parameters?
    it = req.getParameterKeys().iterator();
    while (it.hasNext()) {
        String key = (String) it.next();
        if (reservedParameters.indexOf(key) == -1) {
            c = (Collection) parameterMap.get(key);
            if (c == null) {
                return false;
            }
            conv.retainAll(c);
            if (conv.size() == 0) {
                return false;
            }
        }
    }

    // determine which is "best"
    // TODO add weight parameter
    it = conv.iterator();
    converterName = (String) it.next();

    log.debug("appropriate converter: " + converterName);
    return true;
}

From source file:org.languagetool.rules.de.AgreementRule.java

private boolean agreementWithCategoryRelaxation(AnalyzedTokenReadings token1, AnalyzedTokenReadings token2,
        GrammarCategory categoryToRelax) {
    Set<GrammarCategory> categoryToRelaxSet;
    if (categoryToRelax != null) {
        categoryToRelaxSet = Collections.singleton(categoryToRelax);
    } else {/*www .  j ava 2  s.c  o m*/
        categoryToRelaxSet = Collections.emptySet();
    }
    Set<String> set1 = getAgreementCategories(token1, categoryToRelaxSet, true);
    if (set1 == null) {
        return true; // word not known, assume it's correct
    }
    Set<String> set2 = getAgreementCategories(token2, categoryToRelaxSet, true);
    if (set2 == null) {
        return true;
    }
    set1.retainAll(set2);
    return set1.size() > 0;
}

From source file:org.elasticsearch.cluster.metadata.IndexNameExpressionResolver.java

/**
 * Resolves the search routing if in the expression aliases are used. If expressions point to concrete indices
 * or aliases with no routing defined the specified routing is used.
 *
 * @return routing values grouped by concrete index
 *//*from w  ww  .  j a v  a2  s .  co m*/
public Map<String, Set<String>> resolveSearchRouting(ClusterState state, @Nullable String routing,
        String... expressions) {
    List<String> resolvedExpressions = expressions != null ? Arrays.asList(expressions)
            : Collections.<String>emptyList();
    Context context = new Context(state, IndicesOptions.lenientExpandOpen());
    for (ExpressionResolver expressionResolver : expressionResolvers) {
        resolvedExpressions = expressionResolver.resolve(context, resolvedExpressions);
    }

    if (isAllIndices(resolvedExpressions)) {
        return resolveSearchRoutingAllIndices(state.metaData(), routing);
    }

    if (resolvedExpressions.size() == 1) {
        return resolveSearchRoutingSingleValue(state.metaData(), routing, resolvedExpressions.get(0));
    }

    Map<String, Set<String>> routings = null;
    Set<String> paramRouting = null;
    // List of indices that don't require any routing
    Set<String> norouting = new HashSet<>();
    if (routing != null) {
        paramRouting = Strings.splitStringByCommaToSet(routing);
    }

    for (String expression : resolvedExpressions) {
        ImmutableOpenMap<String, AliasMetaData> indexToRoutingMap = state.metaData().getAliases()
                .get(expression);
        if (indexToRoutingMap != null && !indexToRoutingMap.isEmpty()) {
            for (ObjectObjectCursor<String, AliasMetaData> indexRouting : indexToRoutingMap) {
                if (!norouting.contains(indexRouting.key)) {
                    if (!indexRouting.value.searchRoutingValues().isEmpty()) {
                        // Routing alias
                        if (routings == null) {
                            routings = newHashMap();
                        }
                        Set<String> r = routings.get(indexRouting.key);
                        if (r == null) {
                            r = new HashSet<>();
                            routings.put(indexRouting.key, r);
                        }
                        r.addAll(indexRouting.value.searchRoutingValues());
                        if (paramRouting != null) {
                            r.retainAll(paramRouting);
                        }
                        if (r.isEmpty()) {
                            routings.remove(indexRouting.key);
                        }
                    } else {
                        // Non-routing alias
                        if (!norouting.contains(indexRouting.key)) {
                            norouting.add(indexRouting.key);
                            if (paramRouting != null) {
                                Set<String> r = new HashSet<>(paramRouting);
                                if (routings == null) {
                                    routings = newHashMap();
                                }
                                routings.put(indexRouting.key, r);
                            } else {
                                if (routings != null) {
                                    routings.remove(indexRouting.key);
                                }
                            }
                        }
                    }
                }
            }
        } else {
            // Index
            if (!norouting.contains(expression)) {
                norouting.add(expression);
                if (paramRouting != null) {
                    Set<String> r = new HashSet<>(paramRouting);
                    if (routings == null) {
                        routings = newHashMap();
                    }
                    routings.put(expression, r);
                } else {
                    if (routings != null) {
                        routings.remove(expression);
                    }
                }
            }
        }

    }
    if (routings == null || routings.isEmpty()) {
        return null;
    }
    return routings;
}

From source file:nl.spellenclubeindhoven.dominionshuffle.data.CardSelector.java

/**
 * Pick a Card and remove it from the availableCards List.<br/>
 * If we have any minimumLimit, pick from the smallest (first in list) to satisfy it.
 *///  w  ww .  j  av  a  2 s . c om
private Result pickCard(final Result existingResult, final Set<Card> availableCards) throws SolveError {
    Set<Card> pickSource = availableCards;

    // Check to see if there's still a minimumLimit to satisfy
    for (final Limit minimumLimit : minimumLimits) {
        if (!minimumLimit.minimumSatisfied(existingResult.getCards())) {
            pickSource = new HashSet<>(availableCards);
            pickSource.retainAll(minimumLimit.getGroup().getCards());
            break;
        }
    }

    if (pickSource.isEmpty()) {
        throw new SolveError(R.string.solveerror_rules_to_strict,
                "Can not select cards using given rules, try relaxing them");
    }

    // Randomise selection from the set - Iterating through isn't very efficient, but without writing a combined List Set class ourself is the easiest choice.
    final int cardToFetch = this.random.nextInt(pickSource.size());
    final Iterator<Card> iterator = pickSource.iterator();
    for (int i = 0; i < cardToFetch; i++) {
        iterator.next();
    }
    final Card pickedCard = iterator.next();

    // Remove from the availableList
    availableCards.remove(pickedCard);

    Result result = new Result(existingResult);
    result.addCard(pickedCard);

    return result;
}

From source file:com.glaf.base.modules.sys.rest.SysUserResource.java

/**
 * /*w w  w .j a va  2 s  . co m*/
 * 
 * @param request
 * @param uriInfo
 * @return
 */
@Path("setRole")
@POST
@Produces(MediaType.TEXT_PLAIN)
public ModelAndView setRole(@Context HttpServletRequest request, @Context UriInfo uriInfo) {
    RequestUtils.setRequestParameterToAttribute(request);
    logger.debug(RequestUtils.getParameterMap(request));
    ViewMessages messages = new ViewMessages();
    long userId = ParamUtil.getIntParameter(request, "user_id", 0);
    SysUser user = sysUserService.findById(userId);// 

    if (user != null) {// 
        long[] id = ParamUtil.getLongParameterValues(request, "id");// ???
        if (id != null) {
            Set<SysDeptRole> delRoles = new HashSet<SysDeptRole>();
            Set<SysDeptRole> oldRoles = user.getRoles();
            Set<SysDeptRole> newRoles = new HashSet<SysDeptRole>();
            for (int i = 0; i < id.length; i++) {
                logger.debug("id[" + i + "]=" + id[i]);
                SysDeptRole role = sysDeptRoleService.findById(id[i]);// 
                if (role != null) {
                    newRoles.add(role);// 
                }
            }

            oldRoles.retainAll(newRoles);// ??
            delRoles.removeAll(newRoles);// ??
            newRoles.removeAll(oldRoles);// ??
            user.setUpdateBy(RequestUtils.getActorId(request));

            if (sysUserService.updateRole(user, delRoles, newRoles)) {// ??
                messages.add(ViewMessages.GLOBAL_MESSAGE, new ViewMessage("user.role_success"));
            } else {// ?
                messages.add(ViewMessages.GLOBAL_MESSAGE, new ViewMessage("user.role_failure"));
            }
        }
    }
    MessageUtils.addMessages(request, messages);
    return new ModelAndView("show_json_msg");
}

From source file:org.ut.biolab.medsavant.client.region.RegionWizard.java

private AbstractWizardPage getGenesPage() {
    return new DefaultWizardPage(PAGENAME_GENES) {
        private static final int GENE_SELECTION_PANE_WIDTH = 350;
        private JPanel leftSide;
        private GeneSelectionPanel geneManiaResultsPanel;
        private Set<String> geneManiaGeneNames = null;

        {//from   ww  w.  j  a v a  2  s.com
            selectedGenesPanel = new GeneSelectionPanel(true, true);
            sourceGenesPanel = new GeneSelectionPanel(true, true);
            geneManiaResultsPanel = new GeneSelectionPanel(true, true) {
                @Override
                protected void dragAndDropAddGenes(Set<Gene> geneSet) {
                    Set<Object> genesToMoveToGeneManiaPanel = new HashSet<Object>(geneManiaGeneNames);
                    genesToMoveToGeneManiaPanel.retainAll(selectedGenesPanel.getSelectedKeys());
                    selectedGenesPanel.copyItems(geneManiaResultsPanel, genesToMoveToGeneManiaPanel);
                    selectedGenesPanel.moveSelectedItems(sourceGenesPanel);
                }

                @Override
                protected void dragAndDropRemoveKeys(Set<Object> keySet) {
                    Set<Object> keys = geneManiaResultsPanel.getSelectedKeys();
                    geneManiaResultsPanel.removeRows(keys);
                    sourceGenesPanel.removeRows(keys);
                }
            };
            geneManiaResultsPanel.setOddRowColor(new Color(242, 249, 245));

            runGeneManiaButton = new JButton("Run GeneMANIA");
            runGeneManiaButton.setEnabled(!DirectorySettings.isGeneManiaInstalled());

            ListSelectionListener selectionListener = new ListSelectionListener() {
                @Override
                public void valueChanged(ListSelectionEvent lse) {
                    int numSel = sourceGenesPanel.getNumSelected() + selectedGenesPanel.getNumSelected();
                    if (geneManiaGeneNames != null) {
                        numSel += geneManiaResultsPanel.getNumSelected();
                    }
                    if (GenemaniaInfoRetriever.isGeneManiaDownloading()) {
                        runGeneManiaButton.setEnabled(false);
                    } else {
                        runGeneManiaButton.setEnabled(numSel > 0 || !DirectorySettings.isGeneManiaInstalled());
                    }
                }
            };

            sourceGenesPanel.getTable().getSelectionModel().addListSelectionListener(selectionListener);
            selectedGenesPanel.getTable().getSelectionModel().addListSelectionListener(selectionListener);
            selectedGenesPanel.getTable().getModel().addTableModelListener(new TableModelListener() {
                @Override
                public void tableChanged(TableModelEvent tme) {
                    if (selectedGenesPanel.getData().length > 0) {
                        fireButtonEvent(ButtonEvent.ENABLE_BUTTON, ButtonNames.NEXT);
                    } else {
                        fireButtonEvent(ButtonEvent.DISABLE_BUTTON, ButtonNames.NEXT);
                    }
                }
            });

            selectedGenesPanel.setPreferredSize(
                    new Dimension(GENE_SELECTION_PANE_WIDTH, selectedGenesPanel.getPreferredSize().height));

            final JPanel outerLeftSide = new JPanel();
            outerLeftSide.setLayout(new BoxLayout(outerLeftSide, BoxLayout.X_AXIS));

            leftSide = new JPanel();
            leftSide.setLayout(new BoxLayout(leftSide, BoxLayout.Y_AXIS));
            leftSide.add(sourceGenesPanel);
            outerLeftSide.add(leftSide);
            final JPanel bg = new JPanel();
            bg.setLayout(new BoxLayout(bg, BoxLayout.Y_AXIS));

            JButton addButton = new JButton("Add ");
            JButton removeButton = new JButton("? Remove");

            sourceGenesPanel.getTable().addMouseListener(new MouseAdapter() {
                @Override
                public void mouseClicked(MouseEvent me) {
                    if (me.getClickCount() == 2) {
                        sourceGenesPanel.moveSelectedItems(selectedGenesPanel);
                    }
                }
            });

            selectedGenesPanel.getTable().addMouseListener(new MouseAdapter() {
                @Override
                public void mouseClicked(MouseEvent me) {
                    if (me.getClickCount() == 2) {
                        if (geneManiaGeneNames != null) {
                            Set<Object> genesToMoveToGeneManiaPanel = new HashSet<Object>(geneManiaGeneNames);
                            genesToMoveToGeneManiaPanel.retainAll(selectedGenesPanel.getSelectedKeys());
                            selectedGenesPanel.copyItems(geneManiaResultsPanel, genesToMoveToGeneManiaPanel);
                        }
                        selectedGenesPanel.moveSelectedItems(sourceGenesPanel);
                    }
                }
            });

            geneManiaResultsPanel.getTable().addMouseListener(new MouseAdapter() {
                @Override
                public void mouseClicked(MouseEvent me) {
                    if (me.getClickCount() == 2) {
                        Set<Object> keys = geneManiaResultsPanel.getSelectedKeys();
                        geneManiaResultsPanel.moveSelectedItems(selectedGenesPanel);
                        sourceGenesPanel.moveItems(selectedGenesPanel, keys);
                    }
                }
            });

            addButton.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent ae) {
                    if (geneManiaGeneNames != null) {
                        Set<Object> keys = geneManiaResultsPanel.getSelectedKeys();
                        geneManiaResultsPanel.moveSelectedItems(selectedGenesPanel);
                        sourceGenesPanel.moveItems(selectedGenesPanel, keys);
                    } else {
                        sourceGenesPanel.moveSelectedItems(selectedGenesPanel);
                    }
                }
            });

            removeButton.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent ae) {
                    if (geneManiaGeneNames != null) {
                        Set<Object> genesToMoveToGeneManiaPanel = new HashSet<Object>(geneManiaGeneNames);
                        genesToMoveToGeneManiaPanel.retainAll(selectedGenesPanel.getSelectedKeys());
                        selectedGenesPanel.copyItems(geneManiaResultsPanel, genesToMoveToGeneManiaPanel);
                    }
                    selectedGenesPanel.moveSelectedItems(sourceGenesPanel);
                }
            });

            bg.add(Box.createVerticalGlue());
            bg.add(addButton);
            bg.add(removeButton);
            bg.add(Box.createVerticalGlue());
            outerLeftSide.add(bg);

            JPanel rightSide = new JPanel();
            rightSide.setLayout(new BoxLayout(rightSide, BoxLayout.Y_AXIS));
            rightSide.add(selectedGenesPanel);
            rightSide.add(runGeneManiaButton);

            final JSplitPane hsplitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, outerLeftSide, rightSide);
            hsplitPane.setResizeWeight(1);
            addComponent(hsplitPane, true);

            if (!DirectorySettings.isGeneManiaInstalled()) {
                runGeneManiaButton.setText("Download GeneMANIA");
                if (GenemaniaInfoRetriever.isGeneManiaDownloading()) {
                    runGeneManiaButton.setEnabled(false);
                    registerDownloadListener();
                }
            }

            runGeneManiaButton.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent ae) {

                    if (!DirectorySettings.isGeneManiaInstalled()) {
                        int response = DialogUtils.askYesNo("Download GeneMANIA?",
                                "GeneMANIA is not yet installed.  Do you want to download and install it now?");
                        try {
                            if (response == DialogUtils.OK) {
                                runGeneManiaButton.setText("Run GeneMANIA");
                                runGeneManiaButton.setEnabled(false);
                                registerDownloadListener();

                                /*
                                 DownloadTask dt = GenemaniaInfoRetriever.getGeneManiaDownloadTask();
                                 dt.addPropertyChangeListener(new PropertyChangeListener() {
                                 @Override
                                 public void propertyChange(PropertyChangeEvent evt) {
                                 if (evt.getPropertyName().equals("downloadState")) {
                                 DownloadTask.DownloadState ds = (DownloadTask.DownloadState) evt.getNewValue();
                                 if (ds == DownloadTask.DownloadState.CANCELLED
                                 || ds == DownloadTask.DownloadState.FINISHED) {
                                        
                                 runGeneManiaButton.setEnabled(
                                 (selectedGenesPanel.getNumSelected() + sourceGenesPanel.getNumSelected()) > 0);
                                 }
                                 }
                                 }
                                 });
                                 */
                                GenemaniaInfoRetriever.getGeneManiaDownloadTask().execute();
                            }
                        } catch (IOException e) {
                            DialogUtils.displayMessage("Error downloading GeneMANIA files");
                            LOG.error(e);
                        }
                    } else {

                        final List<String> selectedGenes = new LinkedList<String>();
                        for (Gene g : selectedGenesPanel.getSelectedGenes()) {
                            selectedGenes.add(g.getName());
                        }
                        for (Gene g : sourceGenesPanel.getSelectedGenes()) {
                            selectedGenes.add(g.getName());
                        }
                        if (geneManiaGeneNames != null) {
                            for (Gene g : geneManiaResultsPanel.getSelectedGenes()) {
                                selectedGenes.add(g.getName());
                            }
                        }
                        final JButton closeGeneManiaButton = new JButton("? Close GeneMANIA results");
                        closeGeneManiaButton.setEnabled(false);
                        final JPanel geneManiaContainingPanel = new JPanel();
                        geneManiaContainingPanel
                                .setLayout(new BoxLayout(geneManiaContainingPanel, BoxLayout.Y_AXIS));

                        final SwingWorker geneManiaWorker = new SwingWorker() {
                            private List<Object[]> results;

                            @Override
                            public void done() {
                                Object[][] newdata = new Object[results.size()][4];
                                results.toArray(newdata);
                                geneManiaResultsPanel.updateData(newdata);
                                geneManiaResultsPanel.updateView();
                                geneManiaContainingPanel.removeAll();
                                geneManiaContainingPanel.add(geneManiaResultsPanel);
                                geneManiaContainingPanel.revalidate();
                                geneManiaContainingPanel.repaint();
                                closeGeneManiaButton.setEnabled(true);
                            }

                            @Override
                            public Object doInBackground() {
                                try {
                                    GenemaniaInfoRetriever genemania = new GenemaniaInfoRetriever();
                                    genemania.setGenes(selectedGenes);
                                    List<String> geneNameList = genemania.getRelatedGeneNamesByScore();
                                    geneManiaGeneNames = new HashSet<String>();
                                    geneManiaGeneNames.addAll(geneNameList);
                                    LOG.debug("Found " + geneNameList.size() + " related genes");

                                    results = new ArrayList<Object[]>(geneNameList.size());

                                    int i = 0;
                                    for (String gene : geneNameList) {
                                        if (isCancelled()) {
                                            return null;
                                        }
                                        Gene g = GeneSetFetcher.getInstance().getGeneDictionary().get(gene);
                                        if (g == null) {
                                            LOG.warn("No gene found for " + gene);
                                        } else if (!selectedGenesPanel.hasKey(g.getName())) {
                                            results.add(new Object[] { g.getName(), g.getChrom(), g.getStart(),
                                                    g.getEnd() });
                                        }
                                    }
                                } catch (IOException e) {
                                    LOG.error(e);
                                } catch (ApplicationException e) {
                                    LOG.error(e);
                                } catch (DataStoreException e) {
                                    LOG.error(e);
                                } catch (NoRelatedGenesInfoException e) {
                                    LOG.error(e);
                                }
                                return null;
                            }
                        };

                        leftSide.removeAll();

                        closeGeneManiaButton.addActionListener(new ActionListener() {
                            @Override
                            public void actionPerformed(ActionEvent ae) {
                                try {
                                    geneManiaWorker.cancel(true);
                                } catch (Exception e) {
                                    //genemania throws exceptions when cancelled
                                }
                                leftSide.removeAll();
                                leftSide.add(sourceGenesPanel);
                                leftSide.validate();
                                leftSide.repaint();
                                geneManiaGeneNames = null;
                            }
                        });

                        JPanel closeButtonPanel = new JPanel();
                        closeButtonPanel.setLayout(new BoxLayout(closeButtonPanel, BoxLayout.X_AXIS));
                        closeButtonPanel.add(closeGeneManiaButton);
                        closeButtonPanel.add(Box.createHorizontalGlue());

                        leftSide.add(closeButtonPanel);

                        geneManiaContainingPanel.add(new WaitPanel("Querying GeneMANIA for related genes"));

                        leftSide.add(geneManiaContainingPanel);
                        leftSide.validate();
                        leftSide.repaint();
                        geneManiaWorker.execute();

                    } //end else
                }//end actionPerformed
            });//end ActionListener
        }

        @Override
        public void setupWizardButtons() {
            fireButtonEvent(ButtonEvent.HIDE_BUTTON, ButtonNames.FINISH);
            fireButtonEvent(ButtonEvent.SHOW_BUTTON, ButtonNames.BACK);

            if (selectedGenesPanel.getNumSelected() > 0) {
                fireButtonEvent(ButtonEvent.ENABLE_BUTTON, ButtonNames.NEXT);
            } else {
                fireButtonEvent(ButtonEvent.DISABLE_BUTTON, ButtonNames.NEXT);
            }
        }
    };
}

From source file:opennlp.tools.fca.BasicLevelMetrics.java

public void categoryUtility() {
    if (attributesExtent == null)
        this.setUp();

    ArrayList<Integer> attrExtent;
    Set<Integer> intersection;
    double sum = 0;
    int attrSize = cl.objectCount;
    int cExtentSize = 0;
    for (FormalConcept c : cl.conceptList) {
        sum = 0;/*from  w ww.ja  v a2s  .co m*/
        for (int i = 0; i < cl.attributeCount; i++) {
            intersection = new HashSet<Integer>();
            intersection.addAll(c.extent);
            cExtentSize = c.extent.size();
            attrExtent = attributesExtent.get(i);
            intersection.retainAll(attrExtent);
            sum += (double) Math.pow(intersection.size() * 1. / cExtentSize, 2)
                    - Math.pow(1. * attrExtent.size() / attrSize, 2);
        }
        c.blCU = Double.isNaN(1. * cExtentSize / attrSize * sum) ? 0 : 1. * cExtentSize / attrSize * sum;
    }
}