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:org.apache.aurora.scheduler.async.preemptor.PreemptorImpl.java

@Override
public synchronized Optional<String> findPreemptionSlotFor(final String taskId,
        AttributeAggregate attributeAggregate) {

    final Optional<IAssignedTask> pendingTask = fetchIdlePendingTask(taskId);

    // Task is no longer PENDING no need to preempt.
    if (!pendingTask.isPresent()) {
        return Optional.absent();
    }//ww w.  ja  va2  s.  co  m

    Multimap<String, PreemptionVictim> slavesToActiveTasks = clusterState.getSlavesToActiveTasks();

    if (slavesToActiveTasks.isEmpty()) {
        return Optional.absent();
    }

    attemptedPreemptions.incrementAndGet();

    // Group the offers by slave id so they can be paired with active tasks from the same slave.
    Multimap<String, HostOffer> slavesToOffers = Multimaps.index(offerQueue.getOffers(), OFFER_TO_SLAVE_ID);

    Set<String> allSlaves = ImmutableSet.<String>builder().addAll(slavesToOffers.keySet())
            .addAll(slavesToActiveTasks.keySet()).build();

    for (String slaveID : allSlaves) {
        final Optional<Set<String>> toPreemptTasks = getTasksToPreempt(slavesToActiveTasks.get(slaveID),
                slavesToOffers.get(slaveID), pendingTask.get(), attributeAggregate);

        if (toPreemptTasks.isPresent()) {
            storage.write(new Storage.MutateWork.NoResult.Quiet() {
                @Override
                protected void execute(Storage.MutableStoreProvider storeProvider) {
                    for (String toPreempt : toPreemptTasks.get()) {
                        stateManager.changeState(storeProvider, toPreempt, Optional.<ScheduleStatus>absent(),
                                PREEMPTING, Optional.of("Preempting in favor of " + taskId));
                        tasksPreempted.incrementAndGet();
                    }
                }
            });
            return Optional.of(slaveID);
        }
    }

    noSlotsFound.incrementAndGet();
    return Optional.absent();
}

From source file:eu.interedition.text.rdbms.RelationalAnnotationLinkRepository.java

public Map<AnnotationLink, Set<Annotation>> create(Multimap<Name, Set<Annotation>> links) {
    final Map<Name, Long> nameIdIndex = Maps.newHashMap();
    for (Name n : nameRepository.get(links.keySet())) {
        nameIdIndex.put(n, ((RelationalName) n).getId());
    }/* www  .  j  a  v a  2s. c  o  m*/

    final Map<AnnotationLink, Set<Annotation>> created = Maps.newLinkedHashMap();
    final List<SqlParameterSource> linkBatch = Lists.newArrayList();
    final List<SqlParameterSource> targetBatch = Lists.newArrayList();

    for (Map.Entry<Name, Set<Annotation>> link : links.entries()) {
        final Name linkName = link.getKey();
        final Set<Annotation> targets = link.getValue();

        final Long nameId = nameIdIndex.get(linkName);
        final long linkId = annotationLinkIdIncrementer.nextLongValue();

        linkBatch.add(new MapSqlParameterSource().addValue("id", linkId).addValue("name", nameId));

        for (Annotation target : targets) {
            targetBatch.add(new MapSqlParameterSource().addValue("link", linkId).addValue("target",
                    ((RelationalAnnotation) target).getId()));
        }

        created.put(new RelationalAnnotationLink(new RelationalName(linkName, nameId), linkId), targets);
    }

    annotationLinkInsert.executeBatch(linkBatch.toArray(new SqlParameterSource[linkBatch.size()]));
    annotationLinkTargetInsert.executeBatch(targetBatch.toArray(new SqlParameterSource[targetBatch.size()]));

    return created;
}

From source file:com.github.rinde.jaamas17.ResultWriter.java

@Override
public void doneComputing(ExperimentResults results) {
    final Multimap<MASConfiguration, SimulationResult> groupedResults = LinkedHashMultimap.create();
    for (final SimulationResult sr : results.sortedResults()) {
        groupedResults.put(sr.getSimArgs().getMasConfig(), sr);
    }/* w  w w . j  a  va2s  .c  om*/

    for (final MASConfiguration config : groupedResults.keySet()) {
        final Collection<SimulationResult> group = groupedResults.get(config);

        final File configResult = new File(experimentDirectory, config.getName() + "-final.csv");

        // deletes the file in case it already exists
        configResult.delete();
        createCSVWithHeader(configResult);
        for (final SimulationResult sr : group) {
            appendSimResult(sr, configResult);
        }
    }

}

From source file:com.facebook.buck.android.SmartDexingStep.java

@Override
public int execute(ExecutionContext context) {
    ProjectFilesystem projectFilesystem = context.getProjectFilesystem();
    try {/*  w  ww  . j av  a  2 s .c  o m*/
        Multimap<Path, Path> outputToInputs = outputToInputsSupplier.get();
        runDxCommands(context, outputToInputs);
        if (secondaryOutputDir.isPresent()) {
            removeExtraneousSecondaryArtifacts(secondaryOutputDir.get(), outputToInputs.keySet(),
                    projectFilesystem);
        }
    } catch (StepFailedException | IOException e) {
        context.logError(e, "There was an error in smart dexing step.");
        return 1;
    }

    return 0;
}

From source file:com.eucalyptus.cloudwatch.workflow.alarms.AlarmStateEvaluationDispatcher.java

private List<List<AlarmEntity>> makeResultsList(List<AlarmEntity> results) {
    Multimap<Class, AlarmEntity> classMultiMap = LinkedListMultimap.create();
    for (AlarmEntity alarmEntity : results) {
        classMultiMap.put(MetricEntityFactory.getClassForEntitiesGet(alarmEntity.getMetricType(),
                MetricManager.hash(alarmEntity.getDimensionMap())), alarmEntity);
    }//w  w w. j  a v  a  2s.  com
    List<Iterator<List<AlarmEntity>>> iterators = Lists.newArrayList();
    for (Class clazz : classMultiMap.keySet()) {
        iterators.add(Iterables.partition(classMultiMap.get(clazz), 100).iterator());
    }
    List<List<AlarmEntity>> retVal = Lists.newArrayList();
    boolean atLeastOneMightHaveMore = true;
    while (atLeastOneMightHaveMore) {
        atLeastOneMightHaveMore = false;
        for (Iterator<List<AlarmEntity>> iterator : iterators) {
            if (iterator.hasNext()) {
                atLeastOneMightHaveMore = true;
                retVal.add(iterator.next());
            }
        }
    }
    return retVal;
}

From source file:org.robotframework.ide.eclipse.main.plugin.project.build.validation.KeywordSettingsValidator.java

private Multimap<String, RobotToken> extractArgumentVariables(final UserKeyword keyword,
        final VariableExtractor extractor, final String fileName) {
    final Multimap<String, RobotToken> arguments = ArrayListMultimap.create();

    // first add arguments embedded in name, then from [Arguments] setting
    final Multimap<String, RobotToken> embeddedArguments = VariableNamesSupport
            .extractUnifiedVariables(newArrayList(keyword.getKeywordName()), extractor, fileName);
    for (final String argName : embeddedArguments.keySet()) {
        arguments.putAll(EmbeddedKeywordNamesSupport.removeRegex(argName), embeddedArguments.get(argName));
    }//from ww w  . j  av a2 s  .c o m
    for (final KeywordArguments argument : keyword.getArguments()) {
        for (final RobotToken token : argument.getArguments()) {

            final boolean hasDefault = token.getText().contains("=");
            if (hasDefault) {
                final List<String> splitted = Splitter.on('=').limit(2).splitToList(token.getText());
                final String def = splitted.get(0);
                final String unifiedDefinitionName = VariableNamesSupport.extractUnifiedVariableName(def);
                final Multimap<String, RobotToken> usedVariables = VariableNamesSupport
                        .extractUnifiedVariables(newArrayList(token), new VariableExtractor(), null);
                arguments.put(unifiedDefinitionName,
                        Iterables.getFirst(usedVariables.get(unifiedDefinitionName), null));
            } else {
                arguments.putAll(
                        VariableNamesSupport.extractUnifiedVariables(newArrayList(token), extractor, fileName));
            }
        }
    }
    return arguments;
}

From source file:org.gradle.model.internal.manage.schema.extract.StructSchemaExtractionStrategySupport.java

private <R> List<ModelPropertyExtractionResult<?>> extractPropertySchemas(
        ModelSchemaExtractionContext<R> extractionContext, Multimap<String, Method> methodsByName) {
    List<ModelPropertyExtractionResult<?>> results = Lists.newArrayList();
    Set<Method> handledMethods = Sets.newHashSet();

    List<String> methodNames = Lists.newArrayList(methodsByName.keySet());
    Collections.sort(methodNames);
    Set<String> skippedMethodNames = Sets.newHashSet();
    for (String methodName : methodNames) {
        if (skippedMethodNames.contains(methodName)) {
            continue;
        }//www. j  a v  a  2s  .  c  o  m

        Collection<Method> methods = methodsByName.get(methodName);

        List<Method> overloadedMethods = getOverloadedMethods(methods);
        if (overloadedMethods != null) {
            handleOverloadedMethods(extractionContext, overloadedMethods);
            methods = filterGetterMethods(methods);
            if (methods.isEmpty()) {
                continue;
            }
        }

        int getterPrefixLen = getterPrefixLength(methodName);
        if (getterPrefixLen >= 0) {
            Method mostSpecificGetter = ModelSchemaUtils.findMostSpecificMethod(methods);

            char getterPropertyNameFirstChar = methodName.charAt(getterPrefixLen);
            if (!Character.isUpperCase(getterPropertyNameFirstChar)) {
                handleInvalidGetter(extractionContext, mostSpecificGetter,
                        String.format(
                                "the %s character of the getter method name must be an uppercase character",
                                getterPrefixLen == 2 ? "3rd" : "4th"));
                continue;
            }

            String propertyNameCapitalized = methodName.substring(getterPrefixLen);
            String propertyName = StringUtils.uncapitalize(propertyNameCapitalized);
            String setterName = "set" + propertyNameCapitalized;
            Collection<Method> setterMethods = methodsByName.get(setterName);
            PropertyAccessorExtractionContext setterContext = !setterMethods.isEmpty()
                    ? new PropertyAccessorExtractionContext(setterMethods)
                    : null;

            String prefix = methodName.substring(0, getterPrefixLen);
            Iterable<Method> getterMethods = methods;
            if (prefix.equals("get")) {
                String isGetterName = "is" + propertyNameCapitalized;
                Collection<Method> isGetterMethods = methodsByName.get(isGetterName);
                if (!isGetterMethods.isEmpty()) {
                    List<Method> overloadedIsGetterMethods = getOverloadedMethods(isGetterMethods);
                    if (overloadedIsGetterMethods != null) {
                        handleOverloadedMethods(extractionContext, overloadedIsGetterMethods);
                        isGetterMethods = filterGetterMethods(isGetterMethods);
                    }

                    if (!isGetterMethods.isEmpty()) {
                        Method mostSpecificIsGetter = ModelSchemaUtils.findMostSpecificMethod(isGetterMethods);
                        if (mostSpecificGetter.getReturnType() != boolean.class
                                || mostSpecificIsGetter.getReturnType() != boolean.class) {
                            handleInvalidGetter(extractionContext, mostSpecificIsGetter, String.format(
                                    "property '%s' has both '%s()' and '%s()' getters, but they don't both return a boolean",
                                    propertyName, isGetterName, methodName));
                            continue;
                        }
                        getterMethods = Iterables.concat(getterMethods, isGetterMethods);
                        skippedMethodNames.add(isGetterName);
                    }
                }
            }

            PropertyAccessorExtractionContext getterContext = new PropertyAccessorExtractionContext(
                    getterMethods);
            ModelPropertyExtractionResult<?> result = extractPropertySchema(extractionContext, propertyName,
                    getterContext, setterContext, getterPrefixLen);
            if (result != null) {
                results.add(result);
                handledMethods.addAll(getterContext.getDeclaringMethods());
                if (setterContext != null) {
                    handledMethods.addAll(setterContext.getDeclaringMethods());
                }

            }
        }
    }

    validateAllNecessaryMethodsHandled(extractionContext, methodsByName.values(), handledMethods);
    return results;
}

From source file:org.sonar.batch.issue.tracking.IssueTracking.java

private void mapNewissues(FileHashes hashedReference, FileHashes hashedSource,
        Collection<DefaultIssue> newIssues, IssueTrackingResult result) {

    IssueTrackingBlocksRecognizer rec = new IssueTrackingBlocksRecognizer(hashedReference, hashedSource);

    RollingFileHashes a = RollingFileHashes.create(hashedReference, 5);
    RollingFileHashes b = RollingFileHashes.create(hashedSource, 5);

    Multimap<Integer, DefaultIssue> newIssuesByLines = newIssuesByLines(newIssues, rec, result);
    Multimap<Integer, ServerIssue> lastIssuesByLines = lastIssuesByLines(result.unmatched(), rec);

    Map<Integer, HashOccurrence> map = Maps.newHashMap();

    for (Integer line : lastIssuesByLines.keySet()) {
        int hash = a.getHash(line);
        HashOccurrence hashOccurrence = map.get(hash);
        if (hashOccurrence == null) {
            // first occurrence in A
            hashOccurrence = new HashOccurrence();
            hashOccurrence.lineA = line;
            hashOccurrence.countA = 1;//  ww w  .  j a  v a 2s  .co m
            map.put(hash, hashOccurrence);
        } else {
            hashOccurrence.countA++;
        }
    }

    for (Integer line : newIssuesByLines.keySet()) {
        int hash = b.getHash(line);
        HashOccurrence hashOccurrence = map.get(hash);
        if (hashOccurrence != null) {
            hashOccurrence.lineB = line;
            hashOccurrence.countB++;
        }
    }

    for (HashOccurrence hashOccurrence : map.values()) {
        if (hashOccurrence.countA == 1 && hashOccurrence.countB == 1) {
            // Guaranteed that lineA has been moved to lineB, so we can map all issues on lineA to all issues on lineB
            map(newIssuesByLines.get(hashOccurrence.lineB), lastIssuesByLines.get(hashOccurrence.lineA),
                    result);
            lastIssuesByLines.removeAll(hashOccurrence.lineA);
            newIssuesByLines.removeAll(hashOccurrence.lineB);
        }
    }

    // Check if remaining number of lines exceeds threshold
    if (lastIssuesByLines.keySet().size() * newIssuesByLines.keySet().size() < 250000) {
        List<LinePair> possibleLinePairs = Lists.newArrayList();
        for (Integer oldLine : lastIssuesByLines.keySet()) {
            for (Integer newLine : newIssuesByLines.keySet()) {
                int weight = rec.computeLengthOfMaximalBlock(oldLine, newLine);
                possibleLinePairs.add(new LinePair(oldLine, newLine, weight));
            }
        }
        Collections.sort(possibleLinePairs, LINE_PAIR_COMPARATOR);
        for (LinePair linePair : possibleLinePairs) {
            // High probability that lineA has been moved to lineB, so we can map all Issues on lineA to all Issues on lineB
            map(newIssuesByLines.get(linePair.lineB), lastIssuesByLines.get(linePair.lineA), result);
        }
    }
}

From source file:edu.umn.msi.tropix.webgui.server.forms.validation.SchemaParserImpl.java

private Collection<String> topologicalSort(final Multimap<String, String> dag) {
    // Perform topological sort
    final Map<String, Color> nodeColor = new HashMap<String, Color>(dag.keySet().size());
    for (final String node : dag.keySet()) {
        nodeColor.put(node, Color.WHITE);
    }/*w ww.  j a va2s  . c om*/
    final List<String> sortedNodes = new ArrayList<String>(dag.keySet().size());

    for (final String node : dag.keySet()) {
        if (nodeColor.get(node).equals(Color.WHITE)) {
            this.topologicalSortVisit(node, dag, sortedNodes, nodeColor);
        }
    }

    return sortedNodes;
}

From source file:org.jetbrains.jet.lang.resolve.DeclarationResolver.java

private void reportRedeclarations(@NotNull Multimap<Name, DeclarationDescriptor> descriptorMap) {
    Set<Pair<PsiElement, Name>> redeclarations = Sets.newHashSet();
    for (Name name : descriptorMap.keySet()) {
        Collection<DeclarationDescriptor> descriptors = descriptorMap.get(name);
        if (descriptors.size() > 1) {
            // We mustn't compare PropertyDescriptor with PropertyDescriptor because we do this at OverloadResolver
            for (DeclarationDescriptor descriptor : descriptors) {
                if (descriptor instanceof ClassDescriptor) {
                    for (DeclarationDescriptor descriptor2 : descriptors) {
                        if (descriptor == descriptor2) {
                            continue;
                        }//from  w  w w  .ja va  2 s. c  o  m

                        redeclarations
                                .add(Pair.create(
                                        BindingContextUtils.classDescriptorToDeclaration(
                                                trace.getBindingContext(), (ClassDescriptor) descriptor),
                                        descriptor.getName()));
                        if (descriptor2 instanceof PropertyDescriptor) {
                            redeclarations
                                    .add(Pair.create(
                                            BindingContextUtils.descriptorToDeclaration(
                                                    trace.getBindingContext(), descriptor2),
                                            descriptor2.getName()));
                        }
                    }
                }
            }
        }
    }
    for (Pair<PsiElement, Name> redeclaration : redeclarations) {
        trace.report(REDECLARATION.on(redeclaration.getFirst(), redeclaration.getSecond().getName()));
    }
}