Example usage for com.google.common.collect Multimap keySet

List of usage examples for com.google.common.collect Multimap keySet

Introduction

In this page you can find the example usage for com.google.common.collect Multimap keySet.

Prototype

Set<K> keySet();

Source Link

Document

Returns a view collection of all distinct keys contained in this multimap.

Usage

From source file:edu.isi.karma.modeling.research.approach1.SteinerNodes.java

private void computeCoherenceList() {

    if (nodes == null || nodes.size() == 0)
        return;/*  w  w w.j  a  va2  s  . c  o m*/

    Map<String, Integer> patternSize = new HashMap<String, Integer>();
    Map<String, String> patternGuid = new HashMap<String, String>();
    int guidSize = new RandomGUID().toString().length();

    for (Node n : nodes) {
        for (String p : n.getPatternIds()) {

            Integer size = patternSize.get(p);
            if (size == null)
                patternSize.put(p, 1);
            else
                patternSize.put(p, ++size);

            if (!patternGuid.containsKey(p)) {
                String guid = new RandomGUID().toString();
                patternGuid.put(p, guid);
            }
        }
    }

    // find the maximum pattern size
    int maxPatternSize = 0;
    for (Entry<String, Integer> entry : patternSize.entrySet()) {
        if (entry.getValue().intValue() > maxPatternSize)
            maxPatternSize = entry.getValue().intValue();
    }

    List<String> listOfNodesLargestPatterns = new ArrayList<String>();

    for (Node n : nodes) {
        List<String> patternIds = new ArrayList<String>(n.getPatternIds());
        Collections.sort(patternIds);

        String[] nodeMaxPatterns = new String[maxPatternSize];
        Arrays.fill(nodeMaxPatterns, "");

        for (String p : patternIds) {
            int size = patternSize.get(p).intValue();
            nodeMaxPatterns[size - 1] += patternGuid.get(p);
        }
        for (int i = maxPatternSize - 1; i >= 0; i--) {
            if (nodeMaxPatterns[i] != null && nodeMaxPatterns[i].trim().length() > 0) {
                listOfNodesLargestPatterns.add(nodeMaxPatterns[i]);
                break;
            }
        }
    }

    Function<String, String> stringEqualiy = new Function<String, String>() {
        @Override
        public String apply(final String s) {
            return s;
        }
    };

    Multimap<String, String> index = Multimaps.index(listOfNodesLargestPatterns, stringEqualiy);

    this.coherenceList.clear();
    int x, y;
    for (String s : index.keySet()) {
        if (s.trim().length() == 0)
            continue;
        x = index.get(s).size();
        y = x > 0 ? index.get(s).iterator().next().length() / guidSize : 0;
        CoherenceItem ci = new CoherenceItem(x, y);
        this.coherenceList.add(ci);
    }

    Collections.sort(this.coherenceList);

}

From source file:org.napile.compiler.lang.resolve.processors.DeclarationResolver.java

private void checkRedeclarationsInInnerClassNames() {
    for (MutableClassDescriptor classDescriptor : context.getClasses().values()) {
        Collection<DeclarationDescriptor> allDescriptors = classDescriptor.getScopeForMemberLookup()
                .getOwnDeclaredDescriptors();

        Multimap<Name, DeclarationDescriptor> descriptorMap = HashMultimap.create();
        for (DeclarationDescriptor desc : allDescriptors) {
            if (desc instanceof ClassDescriptor) {
                descriptorMap.put(desc.getName(), desc);
            }/*from w  w  w  .j a  v  a 2 s.c  om*/
        }

        for (Name name : descriptorMap.keySet()) {
            Collection<DeclarationDescriptor> descriptors = descriptorMap.get(name);
            if (descriptors.size() > 1) {
                for (DeclarationDescriptor descriptor : descriptors) {
                    trace.report(REDECLARATION.on(
                            BindingTraceUtil.classDescriptorToDeclaration(trace, (ClassDescriptor) descriptor),
                            descriptor.getName().getName()));
                }
            }
        }
    }
}

From source file:org.apache.drill.exec.work.foreman.FragmentsRunner.java

/**
 * Send remote intermediate fragment to the assigned Drillbit node.
 * Throw exception in case of failure to send the fragment.
 *
 * @param remoteFragmentMap - Map of Drillbit Endpoint to list of PlanFragment's
 *///  w ww .j  ava2s  .co m
private void scheduleRemoteIntermediateFragments(
        final Multimap<DrillbitEndpoint, PlanFragment> remoteFragmentMap) {

    final int numIntFragments = remoteFragmentMap.keySet().size();
    final ExtendedLatch endpointLatch = new ExtendedLatch(numIntFragments);
    final FragmentSubmitFailures fragmentSubmitFailures = new FragmentSubmitFailures();

    // send remote intermediate fragments
    for (final DrillbitEndpoint ep : remoteFragmentMap.keySet()) {
        sendRemoteFragments(ep, remoteFragmentMap.get(ep), endpointLatch, fragmentSubmitFailures);
    }

    final long timeout = drillbitContext.getOptionManager().getLong(ExecConstants.FRAG_RUNNER_RPC_TIMEOUT)
            * numIntFragments;
    if (numIntFragments > 0 && !endpointLatch.awaitUninterruptibly(timeout)) {
        long numberRemaining = endpointLatch.getCount();
        throw UserException.connectionError()
                .message(
                        "Exceeded timeout (%d) while waiting send intermediate work fragments to remote nodes. "
                                + "Sent %d and only heard response back from %d nodes.",
                        timeout, numIntFragments, numIntFragments - numberRemaining)
                .build(logger);
    }

    // if any of the intermediate fragment submissions failed, fail the query
    final List<FragmentSubmitFailures.SubmissionException> submissionExceptions = fragmentSubmitFailures.submissionExceptions;

    if (submissionExceptions.size() > 0) {
        Set<DrillbitEndpoint> endpoints = Sets.newHashSet();
        StringBuilder sb = new StringBuilder();
        boolean first = true;

        for (FragmentSubmitFailures.SubmissionException e : fragmentSubmitFailures.submissionExceptions) {
            DrillbitEndpoint endpoint = e.drillbitEndpoint;
            if (endpoints.add(endpoint)) {
                if (first) {
                    first = false;
                } else {
                    sb.append(", ");
                }
                sb.append(endpoint.getAddress());
            }
        }
        throw UserException.connectionError(submissionExceptions.get(0).rpcException)
                .message("Error setting up remote intermediate fragment execution")
                .addContext("Nodes with failures", sb.toString()).build(logger);
    }
}

From source file:ca.sqlpower.architect.enterprise.ArchitectNetworkConflictResolver.java

/**
 * Returns a set of strings indicating which columns were pointed to
 * as a result of column mapping property changes, found in the given properties map.
 * The format of the strings are {relationshipId}:{columnId}
 *//*w  w w .  j a  v  a 2 s .  c  o  m*/
private Set<String> getColumnMappingChanges(Multimap<String, PersistedSPOProperty> properties) {
    Set<String> changes = new HashSet<String>();
    for (String uuid : properties.keySet()) {
        Class<?> type;
        String parentId;
        SPObject spo = session.getWorkspace().getObjectInTree(uuid);
        PersistedSPObject o = outboundObjectsToAdd.get(uuid);
        try {
            if (spo != null) {
                type = spo.getClass();
                parentId = spo.getParent().getUUID();
            } else if (o != null) {
                type = Class.forName(o.getType(), true,
                        ArchitectNetworkConflictResolver.class.getClassLoader());
                parentId = o.getParentUUID();
            } else {
                continue;
            }
            if (ColumnMapping.class.isAssignableFrom(type)) {
                for (PersistedSPOProperty p : properties.get(uuid)) {
                    if (p.getDataType() == DataType.REFERENCE) {
                        changes.add(parentId + ":" + (String) p.getNewValue());
                    }
                }
            }
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }
    return changes;
}

From source file:uk.ac.ebi.apps.benchmark.ChemicalNameSearch.java

private SummaryStatistics getHitIndices(Multimap<String, Set<String>> results, FingerprintEncoder encoder) {

    SummaryStatistics summaryStatistics = new SummaryStatistics();

    QUERY: for (String name : results.keySet()) {

        String normName = encoder.encode(name);

        StringBuffer buffer = new StringBuffer();

        List<Set<String>> hits = new ArrayList<Set<String>>(results.get(name));

        for (int i = 0; i < hits.size(); i++) {

            Set<String> hitNames = hits.get(i);

            for (String hit : hitNames) {

                String normHit = encoder.encode(hit);

                buffer.append("\t").append(hit);
                buffer.append("\t").append(normHit);
                buffer.append("\t").append(StringUtils.getLevenshteinDistance(normName, normHit));
                buffer.append("\n");

                if (normName.equals(normHit)) {
                    summaryStatistics.addValue(i + 1);
                    continue QUERY;
                }//  www  .ja  v a  2s.co m

            }

        }

    }

    return summaryStatistics;

}

From source file:prm4j.spec.finite.FiniteParametricProperty.java

/**
 * Returns a mapping of parameter set X to a set of parameter sets {...,X',...} such that an monitor for instance i
 * with Dom(i) = X is alive, when there exists an X' such that all bindings i(x) for all x in X' are alive.
 *///  w  w  w.j  av  a 2  s  .com
@Override
public SetMultimap<Set<Parameter<?>>, Set<Parameter<?>>> getAliveParameterSets() {
    final SetMultimap<MonitorState, Set<Parameter<?>>> state2aliveParameterSets = getState2AliveParameterSets();
    final FSMVisitor visitor = new FSMVisitor(finiteSpec.getBaseEvents());
    visitor.visit(partEnableInitialState);
    Multimap<Set<Parameter<?>>, MonitorState> paramSet2monitorStates = reverseSetMultimap(
            toParameterSetMultimap(visitor.getState2InducedEventSets()));
    final SetMultimap<Set<Parameter<?>>, Set<Parameter<?>>> result = HashMultimap.create();
    for (Set<Parameter<?>> parameterSet : paramSet2monitorStates.keySet()) {
        final Set<Set<Parameter<?>>> parameterSets = new HashSet<Set<Parameter<?>>>();
        for (MonitorState monitorState : paramSet2monitorStates.get(parameterSet)) {
            state2aliveParameterSets.keySet().contains(monitorState);
            parameterSets.addAll(state2aliveParameterSets.get(monitorState));
        }
        result.get(parameterSet).addAll(toSubsetMinimalParameterSets(parameterSets));
    }
    return result;
}

From source file:org.sosy_lab.cpachecker.util.StateToFormulaWriter.java

/** write the definitions and predicates in the commonly used precision-format
 *  (that is defined somewhere else...)*/
private void writeFormulas(Appendable pAppendable, Set<String> definitions,
        Multimap<CFANode, String> cfaNodeToPredicate) throws IOException {

    // write definitions to file
    LINE_JOINER.appendTo(pAppendable, definitions);
    pAppendable.append("\n\n");

    // write states to file
    for (CFANode cfaNode : cfaNodeToPredicate.keySet()) {
        pAppendable.append(toKey(cfaNode));
        pAppendable.append(":\n");
        LINE_JOINER.appendTo(pAppendable, cfaNodeToPredicate.get(cfaNode));
        pAppendable.append("\n\n");
    }//from   ww  w. j  a v  a  2 s .  co  m
}

From source file:com.android.tools.idea.gradle.variant.view.ModuleVariantsInfoDialog.java

@NotNull
private static JTree createDependentsTree(@NotNull Module module, @NotNull AndroidModuleModel androidModel) {
    VariantCheckboxTreeCellRenderer renderer = new VariantCheckboxTreeCellRenderer() {
        @Override//from  w  ww. j  a  va 2 s .c om
        public void customizeRenderer(JTree tree, Object value, boolean selected, boolean expanded,
                boolean leaf, int row, boolean hasFocus) {
            if (value instanceof DefaultMutableTreeNode) {
                Object data = ((DefaultMutableTreeNode) value).getUserObject();
                if (data instanceof String) {
                    appendVariant((String) data);
                } else if (data instanceof DependentTreeElement) {
                    DependentTreeElement dependent = (DependentTreeElement) data;
                    String variant = null;
                    if (!dependent.myVariants.isEmpty()) {
                        variant = Joiner.on(", ").join(dependent.myVariants);
                    }
                    appendModule(dependent.myModule, variant);
                }
            }
        }
    };

    //noinspection ConstantConditions
    CheckedTreeNode root = new CheckedTreeNode(null);

    AndroidProject androidProject = GradleUtil.getAndroidProject(module);
    assert androidProject != null;

    String gradlePath = GradleUtil.getGradlePath(module);
    assert gradlePath != null;

    Multimap<String, DependentTreeElement> dependentsByVariant = HashMultimap.create();

    ModuleManager moduleManager = ModuleManager.getInstance(module.getProject());
    for (Module dependent : moduleManager.getModuleDependentModules(module)) {
        AndroidProject dependentProject = GradleUtil.getAndroidProject(dependent);
        if (dependentProject == null) {
            continue;
        }

        DependentTreeElement element = new DependentTreeElement(dependent);

        for (Variant variant : dependentProject.getVariants()) {
            for (AndroidLibrary library : GradleUtil.getDirectLibraryDependencies(variant, androidModel)) {
                if (gradlePath.equals(library.getProject())) {
                    element.addVariant(variant.getName());
                    String projectVariant = library.getProjectVariant();
                    if (StringUtil.isNotEmpty(projectVariant)) {
                        dependentsByVariant.put(projectVariant, element);
                    }
                }
            }
        }
    }

    List<String> variantNames = Lists.newArrayList(dependentsByVariant.keySet());
    Collections.sort(variantNames);

    for (String variantName : variantNames) {
        Collection<DependentTreeElement> dependents = dependentsByVariant.get(variantName);
        if (!dependents.isEmpty()) {
            List<DependentTreeElement> sortedDependents = Lists.newArrayList(dependents);
            Collections.sort(sortedDependents);

            DefaultMutableTreeNode variantNode = new DefaultMutableTreeNode(variantName);
            for (DependentTreeElement dependent : dependents) {
                variantNode.add(new DefaultMutableTreeNode(dependent));
            }

            root.add(variantNode);
        }
    }

    CheckboxTree tree = new CheckboxTree(renderer, root);
    tree.setRootVisible(false);
    TreeUtil.expandAll(tree);

    return tree;
}

From source file:com.b2international.snowowl.snomed.reasoner.server.classification.EquivalentConceptMerger.java

public void fixEquivalencies() {
    // First resolve the equivalencies Map, to find the equivalent concept instances
    final Multimap<Concept, Concept> equivalentConcepts = resolveEquivalencies();
    final Iterable<Concept> concepts = Iterables.concat(equivalentConcepts.keySet(),
            equivalentConcepts.values());
    final Iterable<String> destinationIds = Iterables.transform(concepts, Concept::getId);
    SnomedRelationships inboundRelationships = SnomedRequests.prepareSearchRelationship().all()
            .filterByActive(true).filterByDestination(destinationIds)
            .build(SnomedDatastoreActivator.REPOSITORY_UUID, editingContext.getBranch())
            .execute(ApplicationContext.getServiceForClass(IEventBus.class)).getSync();
    final Multimap<String, Relationship> inboundRelationshipMap = HashMultimap.create(FluentIterable
            .from(inboundRelationships)/*  w w  w  . j ava  2s  .  c om*/
            .transform(relationship -> (Relationship) editingContext.lookup(relationship.getStorageKey()))
            //Exclude relationships that were already marked redundant
            .filter(relationship -> relationship.getSource() != null && relationship.getDestination() != null)
            .index(relationship -> relationship.getDestination().getId()));
    for (Relationship relationship : ComponentUtils2.getNewObjects(editingContext.getTransaction(),
            Relationship.class)) {
        inboundRelationshipMap.put(relationship.getDestination().getId(), relationship);
    }
    for (Relationship relationship : ComponentUtils2.getDetachedObjects(editingContext.getTransaction(),
            Relationship.class)) {
        inboundRelationshipMap.values().remove(relationship);
    }

    // iterate over the sorted concepts and switch to the equivalent using
    // the resolved Map
    try {
        for (final Concept conceptToKeep : equivalentConcepts.keySet()) {
            final Collection<Concept> conceptsToRemove = equivalentConcepts.get(conceptToKeep);
            switchToEquivalentConcept(conceptToKeep, conceptsToRemove, inboundRelationshipMap,
                    equivalentConcepts);
            removeOrDeactivate(conceptsToRemove);
        }

    } catch (ConflictException e) {
        throw new SnowowlRuntimeException(e);
    }
}

From source file:org.eclipse.sirius.business.internal.session.danalysis.SessionResourcesSynchronizer.java

@Override
public void statusesChanged(Collection<ResourceStatusChange> changes) {
    if (session.isOpen()) {
        Multimap<ResourceStatus, Resource> newStatuses = getImpactingNewStatuses(changes);
        boolean allResourcesSync = allResourcesAreInSync();
        for (ResourceStatus newStatus : newStatuses.keySet()) {
            switch (newStatus) {
            case SYNC:
                if (allResourcesSync) {
                    session.notifyListeners(SessionListener.SYNC);
                }/* w  w  w  .ja  v  a  2s  . co m*/
                break;
            case CHANGED:
                session.notifyListeners(SessionListener.DIRTY);
                break;
            case EXTERNAL_CHANGED:
            case CONFLICTING_CHANGED:
            case CONFLICTING_DELETED:
            case DELETED:
            case CHANGES_CANCELED:
                IProgressMonitor pm = new NullProgressMonitor();
                for (Resource resource : newStatuses.get(newStatus)) {
                    try {
                        /*
                         * if the project was renamed, deleted or closed we
                         * should not try to reload any thing, this does not
                         * make sense
                         */
                        if (isInProjectDeletedRenamedOrClosed(resource)) {
                            processAction(Action.CLOSE_SESSION, resource, pm);
                            return;
                        }
                        processActions(session.getReloadingPolicy().getActions(session, resource, newStatus),
                                resource, pm);

                        // CHECKSTYLE:OFF
                    } catch (final Exception e) {
                        // CHECKSTYLE:ON
                        SiriusPlugin.getDefault()
                                .error(MessageFormat.format(
                                        Messages.SessionResourcesSynchronizer_cantHandleResourceChangeMsg,
                                        resource.getURI()), e);

                    }
                }
                // Reload were launched, get global status.
                allResourcesSync = allResourcesAreInSync();
                if (allResourcesSync) {
                    session.notifyListeners(SessionListener.SYNC);
                } else {
                    session.notifyListeners(SessionListener.DIRTY);
                }
                break;
            default:
                break;
            }
        }

        if (allResourcesSync) {
            session.setSynchronizationStatus(SyncStatus.SYNC);
        } else {
            session.setSynchronizationStatus(SyncStatus.DIRTY);
        }
    }
}