Example usage for com.google.common.collect SetMultimap get

List of usage examples for com.google.common.collect SetMultimap get

Introduction

In this page you can find the example usage for com.google.common.collect SetMultimap get.

Prototype

@Override
Set<V> get(@Nullable K key);

Source Link

Document

Because a SetMultimap has unique values for a given key, this method returns a Set , instead of the java.util.Collection specified in the Multimap interface.

Usage

From source file:com.eviware.loadui.impl.statistics.AgentDataAggregator.java

private synchronized void flush(SetMultimap<String, Entry> map) {
    for (String trackId : map.keySet()) {
        Track track = executionManager.getTrack(trackId);
        if (track == null) {
            continue;
        }/*w  w w .j  av  a  2  s  .  c  o m*/

        EntryAggregator aggregator = track.getTrackDescriptor().getEntryAggregator();

        if (aggregator != null) {
            Entry entry = aggregator.aggregate(map.get(trackId), true);

            if (entry != null)
                statisticsInterpolator.update(entry, trackId, StatisticVariable.MAIN_SOURCE);
        }
    }
}

From source file:dagger.internal.codegen.ComponentProcessingStep.java

@Override
public final ImmutableSet<Element> process(
        SetMultimap<Class<? extends Annotation>, Element> elementsByAnnotation, boolean anyElementsRejected) {

    ImmutableSet.Builder<Element> rejectedElements = ImmutableSet.builder();

    Map<Element, ValidationReport<TypeElement>> builderReportsByComponent = processBuilders(
            elementsByAnnotation.get(componentKind.builderAnnotationType()));
    Set<Element> subcomponentBuilderElements = getElementsFromAnnotations(elementsByAnnotation,
            FluentIterable.from(componentKind.subcomponentKinds())
                    .transform(ComponentDescriptor.Kind::builderAnnotationType).toSet());
    Map<Element, ValidationReport<TypeElement>> builderReportsBySubcomponent = processBuilders(
            subcomponentBuilderElements);
    Set<Element> subcomponentElements = getElementsFromAnnotations(elementsByAnnotation,
            FluentIterable.from(componentKind.subcomponentKinds())
                    .transform(ComponentDescriptor.Kind::annotationType).toSet());
    Map<Element, ValidationReport<TypeElement>> reportsBySubcomponent = processSubcomponents(
            subcomponentElements, subcomponentBuilderElements);

    final Set<Element> elements = elementsByAnnotation.get(componentKind.annotationType());
    for (Element element : elements) {
        TypeElement componentTypeElement = MoreElements.asType(element);
        try {/*ww  w .  j ava 2  s. c  o  m*/
            ComponentValidationReport validationReport = componentValidator.validate(componentTypeElement,
                    subcomponentElements, subcomponentBuilderElements);
            validationReport.report().printMessagesTo(messager);
            if (isClean(validationReport, builderReportsByComponent, reportsBySubcomponent,
                    builderReportsBySubcomponent)) {
                ComponentDescriptor componentDescriptor = componentDescriptorFactory
                        .forComponent(componentTypeElement);
                ValidationReport<TypeElement> hierarchyReport = componentHierarchyValidator
                        .validate(componentDescriptor);
                hierarchyReport.printMessagesTo(messager);
                if (hierarchyReport.isClean()) {
                    BindingGraph bindingGraph = bindingGraphFactory.create(componentDescriptor);
                    ValidationReport<TypeElement> graphReport = bindingGraphValidator.validate(bindingGraph);
                    graphReport.printMessagesTo(messager);
                    if (graphReport.isClean()) {
                        generateComponent(bindingGraph);
                    }
                }
            }
        } catch (TypeNotPresentException e) {
            rejectedElements.add(componentTypeElement);
        }
    }

    final ImmutableSet<Element> failedElements = rejectedElements.build();

    return failedElements;
}

From source file:org.gradle.execution.TaskSelector.java

public TaskSelection getSelection(String path) {
    SetMultimap<String, Task> tasksByName;
    ProjectInternal project = gradle.getDefaultProject();
    ResolvedTaskPath taskPath = taskPathResolver.resolvePath(path, project);

    if (taskPath.isQualified()) {
        tasksByName = taskNameResolver.select(taskPath.getTaskName(), taskPath.getProject());
    } else {/*from w ww.  j a va2  s . c om*/
        tasksByName = taskNameResolver.selectAll(path, project);
    }

    Set<Task> tasks = tasksByName.get(taskPath.getTaskName());
    if (!tasks.isEmpty()) {
        // An exact match
        return new TaskSelection(path, tasks);
    }

    NameMatcher matcher = new NameMatcher();
    String actualName = matcher.find(taskPath.getTaskName(), tasksByName.keySet());

    if (actualName != null) {
        // A partial match
        return new TaskSelection(taskPath.getPrefix() + actualName, tasksByName.get(actualName));
    }

    throw new TaskSelectionException(matcher.formatErrorMessage("task", project));
}

From source file:org.grouplens.grapht.InjectionContainer.java

private Map<Desire, Instantiator> makeDependencyMap(DAGNode<Component, Dependency> node,
        SetMultimap<DAGNode<Component, Dependency>, DAGEdge<Component, Dependency>> backEdges) {
    Set<DAGEdge<Component, Dependency>> edges = node.getOutgoingEdges();
    if (backEdges.containsKey(node)) {
        ImmutableSet.Builder<DAGEdge<Component, Dependency>> bld = ImmutableSet.builder();
        edges = bld.addAll(edges).addAll(backEdges.get(node)).build();
    }//from ww  w .j  a  v  a2s. c o m

    ImmutableSet.Builder<Desire> desires = ImmutableSet.builder();
    for (DAGEdge<Component, Dependency> edge : edges) {
        desires.add(edge.getLabel().getInitialDesire());
    }
    return Maps.asMap(desires.build(), new DepLookup(edges, backEdges));
}

From source file:edu.cmu.lti.oaqa.baseqa.answer.generate.generators.ChoiceCavGenerator.java

@Override
public List<CandidateAnswerVariant> generate(JCas jcas) throws AnalysisEngineProcessException {
    List<Token> tokens = TypeUtil.getOrderedTokens(jcas);
    SetMultimap<Token, Token> head2children = CavUtil.getHeadTokenMap(tokens);
    Token orToken;//  www .j a  va2 s.  c om
    try {
        orToken = tokens.stream().filter(t -> OR_LEMMA.equals(t.getLemmaForm())).findAny().get();
    } catch (NoSuchElementException e) {
        return new ArrayList<>();
    }
    // identify head tokens for choices from the question
    Token mainToken = orToken.getHead();
    List<Token> alternativeTokens = head2children.get(mainToken).stream()
            .filter(t -> CONJ_DEP_LABEL.equals(t.getDepLabel())).collect(toList());
    List<CandidateAnswerVariant> cavs = Stream.concat(Stream.of(mainToken), alternativeTokens.stream())
            .map(token -> CavUtil.createCandidateAnswerVariant(jcas, token)).collect(toList());
    // find CAVs from evidence passages
    Stream.concat(Stream.of(mainToken), alternativeTokens.stream())
            .map(token -> JCasUtil.selectCovering(ConceptMention.class, token)).flatMap(Collection::stream)
            .map(ConceptMention::getConcept).map(concept -> CavUtil.createCandidateAnswerVariant(jcas, concept))
            .forEach(cavs::add);
    return cavs;
}

From source file:org.jakstab.analysis.explicit.VpcTrackingAnalysis.java

@Override
public Pair<AbstractState, Precision> prec(AbstractState s, Precision precision, ReachedSet reached) {

    // This method uses the fact that there is only 1 precision per location

    VpcPrecision vprec = (VpcPrecision) precision;
    BasedNumberValuation widenedState = (BasedNumberValuation) s;
    ExplicitPrecision eprec = vprec.getPrecision(widenedState.getValue(vpc));

    // Only check value counts if we have at least enough states to reach it
    if (reached.size() > Math.min(BoundedAddressTracking.varThreshold.getValue(),
            BoundedAddressTracking.heapThreshold.getValue())) {

        boolean changed = false;

        // Check value counts for variables
        for (RTLVariable v : eprec.varMap.keySet()) {
            //BasedNumberElement currentValue = ((BasedNumberValuation)s).getValue(v);
            Set<BasedNumberElement> existingValues = eprec.varMap.get(v);
            int threshold = eprec.getThreshold(v);
            if (existingValues.size() > threshold) {
                // Lower precisions and widen the value in this state, too.
                // This avoids values accumulating at join points (where they are not
                // intercepted by the precision-aware setValue)
                if (countRegions(existingValues) > threshold) {
                    eprec.stopTracking(v);
                    if (!changed) {
                        widenedState = new BasedNumberValuation(widenedState);
                        changed = true;//from w  w w  . j ava2s.c o  m
                    }
                    widenedState.setValue(v, BasedNumberElement.getTop(v.getBitWidth()));
                } else {
                    eprec.trackRegionOnly(v);
                    if (!changed) {
                        widenedState = new BasedNumberValuation(widenedState);
                        changed = true;
                    }
                    logger.debug("Only tracking region of " + v + ", values were " + existingValues);
                    widenedState.setValue(v, new BasedNumberElement(widenedState.getValue(v).getRegion(),
                            NumberElement.getTop(v.getBitWidth())));
                }
            }
        }

        // Check value counts for store
        PartitionedMemory<BasedNumberElement> sStore = ((BasedNumberValuation) s).getStore();
        for (EntryIterator<MemoryRegion, Long, BasedNumberElement> entryIt = sStore.entryIterator(); entryIt
                .hasEntry(); entryIt.next()) {
            MemoryRegion region = entryIt.getLeftKey();
            Long offset = entryIt.getRightKey();
            BasedNumberElement value = entryIt.getValue();
            SetMultimap<Long, BasedNumberElement> memoryMap = eprec.regionMaps.get(region);
            if (memoryMap == null)
                continue;

            //BasedNumberElement currentValue = entry.getValue();
            Set<BasedNumberElement> existingValues = memoryMap.get(offset);

            int threshold = eprec.getStoreThreshold(region, offset);
            if (existingValues.size() > threshold) {
                if (countRegions(existingValues) > 5 * threshold) {
                    eprec.stopTracking(region, offset);
                    if (!changed) {
                        widenedState = new BasedNumberValuation(widenedState);
                        changed = true;
                    }
                    widenedState.getStore().set(region, offset, value.getBitWidth(),
                            BasedNumberElement.getTop(value.getBitWidth()));
                } else {
                    eprec.trackRegionOnly(region, offset);
                    if (!changed) {
                        widenedState = new BasedNumberValuation(widenedState);
                        changed = true;
                    }
                    widenedState.getStore().set(region, offset, value.getBitWidth(), new BasedNumberElement(
                            value.getRegion(), NumberElement.getTop(value.getBitWidth())));
                }
            }
        }
    }

    // Collect all values for all variables
    for (Map.Entry<RTLVariable, BasedNumberElement> entry : widenedState.getVariableValuation()) {
        eprec.varMap.put(entry.getKey(), entry.getValue());
    }

    // Collect all values for all memory areas
    PartitionedMemory<BasedNumberElement> store = widenedState.getStore();
    for (EntryIterator<MemoryRegion, Long, BasedNumberElement> entryIt = store.entryIterator(); entryIt
            .hasEntry(); entryIt.next()) {
        SetMultimap<Long, BasedNumberElement> memoryMap = eprec.regionMaps.get(entryIt.getLeftKey());
        if (memoryMap == null) {
            memoryMap = HashMultimap.create();
            eprec.regionMaps.put(entryIt.getLeftKey(), memoryMap);
        }
        memoryMap.put(entryIt.getRightKey(), entryIt.getValue());
    }

    // If it was changed, widenedState is now a new state
    return Pair.create((AbstractState) widenedState, precision);
}

From source file:dk.dma.dmiweather.service.ForecastContainer.java

GridResponse getData(GridRequest request, boolean removeEmpty, boolean gridMetrics) {

    Map<GridParameterType, GribFileWrapper> sources = findSources(request);

    if (sources.isEmpty()) {
        throw new APIException(ErrorMessage.OUTSIDE_GRID,
                "There is no grid that contains the entire are, try with a smaller area.");
    }//from   w w  w  .  j av a  2 s .  co  m

    @SuppressWarnings("ConstantConditions") // we have already check if the map was empty
    GribFileWrapper smallestResolution = sources.values().stream().sorted(GribFileWrapper.SMALLEST_RESOLUTION)
            .findFirst().get();

    double dx = smallestResolution.getDx();
    double dy = smallestResolution.getDy();

    GeoCoordinate northWest = request.getNorthWest();
    GeoCoordinate southEast = request.getSouthEast();

    double lonDistance = southEast.getLon() - northWest.getLon();
    double latDistance = northWest.getLat() - southEast.getLat();
    int nativeNx = (int) Math.round(lonDistance / dx) + 1;
    int nativeNy = (int) Math.round(latDistance / dy) + 1;
    int Nx, Ny;
    double latSpacing = 0, lonSpacing = 0;
    if (request.getNx() == null) {
        // use resolution of the smallest data series
        Nx = nativeNx;
        Ny = nativeNy;
        lonSpacing = dx;
        latSpacing = dy;
    } else {
        // if the desired Nx, Ny is higher than the native resolution, we default to the native resolution

        if (nativeNx < request.getNx() || nativeNy < request.getNy()) {
            Nx = nativeNx;
            Ny = nativeNy;
        } else {
            Nx = request.getNx();
            Ny = request.getNy();
        }

        // spacing between points, we always include a point on the boundary, hence the +dx/dy
        if (Ny > 1) {
            latSpacing = (latDistance) / (Ny - 1);
        }
        if (Nx > 1) {
            lonSpacing = (lonDistance) / (Nx - 1);
        }
    }

    ArrayList<GridDataPoint> points = new ArrayList<>(Nx * Ny);
    for (int y = 0; y < Ny; y++) {
        for (int x = 0; x < Nx; x++) {
            double lon = northWest.getLon() + x * lonSpacing;
            double lat = southEast.getLat() + y * latSpacing;
            if (coordinateRounding != -1) {
                lon = MathUtil.round(lon, coordinateRounding);
                lat = MathUtil.round(lat, coordinateRounding);
            }
            points.add(new GridDataPoint().setCoordinate(new GeoCoordinate(lon, lat)));
        }
    }

    // process the data
    for (Map.Entry<GridParameterType, GribFileWrapper> entry : sources.entrySet()) {
        GribFileWrapper file = entry.getValue();
        GridParameterType type = entry.getKey();

        float[] data = file.getDataProviders().get(type).getData(northWest, southEast, Nx, Ny, lonSpacing,
                latSpacing);
        for (int i = 0; i < points.size(); i++) {
            GridDataPoint point = points.get(i);
            if (data[i] != GRIB_NOT_DEFINED) {
                point.setData(type, data[i]);
            }
        }
    }

    if (removeEmpty) {
        points.removeIf(p -> !p.hasValues());
    }

    ArrayList<ForecastInfo> forecasts = new ArrayList<>();
    Set<GridParameterType> missingParameters = request.getParameters().getParamTypes();

    // find the parameter which come from the same File, so we can group forecast parameters
    SetMultimap<GribFileWrapper, GridParameterType> parametersByFile = groupByFile(sources);
    for (GribFileWrapper file : parametersByFile.keySet()) {
        Set<GridParameterType> parametersInFile = parametersByFile.get(file);
        forecasts.add(
                new ForecastInfo().setName(file.getConfiguration().name()).setCreationDate(file.getCreation())
                        .setParameters(GridParameters.parametersFromTypes(parametersInFile)));

        missingParameters.removeAll(parametersInFile);
    }

    GridResponse response = new GridResponse().setPoints(points).setForecasts(forecasts)
            .setQueryTime(Instant.now());

    // set the deprecate time to the first forecast time
    response.setForecastDate(instant);

    if (!missingParameters.isEmpty()) {
        WarningMessage msg = WarningMessage.MISSING_DATA;
        response.setWarning(new JSonWarning().setId(msg.getId()).setMessage(msg.getMessage())
                .setDetails("There was no data for the following parameters, "
                        + missingParameters.stream().map(Object::toString).collect(Collectors.joining(","))));
    }

    if (gridMetrics) {
        response.setDx(lonSpacing);
        response.setDy(latSpacing);
        response.setNx(Nx);
        response.setNy(Ny);
        if (!removeEmpty) {
            GeoCoordinate first = points.get(0).getCoordinate();
            GeoCoordinate last = points.get(points.size() - 1).getCoordinate();
            response.setNorthWest(new GeoCoordinate(first.getLon(), last.getLat()));
            response.setSouthEast(new GeoCoordinate(last.getLon(), first.getLat()));
        }
    }
    return response;
}

From source file:org.jakstab.analysis.explicit.BoundedAddressTracking.java

@Override
public Pair<AbstractState, Precision> prec(AbstractState s, Precision precision, ReachedSet reached) {

    // This method uses the fact that there is only 1 precision per location

    ExplicitPrecision eprec = (ExplicitPrecision) precision;
    BasedNumberValuation widenedState = (BasedNumberValuation) s;

    // Only check value counts if we have at least enough states to reach it
    if (reached.size() > Math.min(varThreshold.getValue(), heapThreshold.getValue())) {

        boolean changed = false;

        // Check value counts for variables
        for (RTLVariable v : eprec.varMap.keySet()) {
            //BasedNumberElement currentValue = ((BasedNumberValuation)s).getValue(v);
            Set<BasedNumberElement> existingValues = eprec.varMap.get(v);
            int threshold = eprec.getThreshold(v);
            if (existingValues.size() > threshold) {
                // Lower precisions and widen the value in this state, too.
                // This avoids values accumulating at join points (where they are not
                // intercepted by the precision-aware setValue)
                if (countRegions(existingValues) > threshold) {
                    eprec.stopTracking(v);
                    if (!changed) {
                        widenedState = new BasedNumberValuation(widenedState);
                        changed = true;//  w w  w. j  a v a2  s  . c  om
                    }
                    widenedState.setValue(v, BasedNumberElement.getTop(v.getBitWidth()));
                } else {
                    eprec.trackRegionOnly(v);
                    if (!changed) {
                        widenedState = new BasedNumberValuation(widenedState);
                        changed = true;
                    }
                    logger.debug("Only tracking region of " + v + ", values were " + existingValues);
                    widenedState.setValue(v, new BasedNumberElement(widenedState.getValue(v).getRegion(),
                            NumberElement.getTop(v.getBitWidth())));
                }
            }
        }

        // Check value counts for store
        PartitionedMemory<BasedNumberElement> sStore = ((BasedNumberValuation) s).getStore();
        for (EntryIterator<MemoryRegion, Long, BasedNumberElement> entryIt = sStore.entryIterator(); entryIt
                .hasEntry(); entryIt.next()) {
            MemoryRegion region = entryIt.getLeftKey();
            Long offset = entryIt.getRightKey();
            BasedNumberElement value = entryIt.getValue();
            SetMultimap<Long, BasedNumberElement> memoryMap = eprec.regionMaps.get(region);
            if (memoryMap == null)
                continue;

            //BasedNumberElement currentValue = entry.getValue();
            Set<BasedNumberElement> existingValues = memoryMap.get(offset);

            int threshold = eprec.getStoreThreshold(region, offset);
            if (existingValues.size() > threshold) {
                if (countRegions(existingValues) > 5 * threshold) {
                    eprec.stopTracking(region, offset);
                    if (!changed) {
                        widenedState = new BasedNumberValuation(widenedState);
                        changed = true;
                    }
                    widenedState.getStore().set(region, offset, value.getBitWidth(),
                            BasedNumberElement.getTop(value.getBitWidth()));
                } else {
                    eprec.trackRegionOnly(region, offset);
                    if (!changed) {
                        widenedState = new BasedNumberValuation(widenedState);
                        changed = true;
                    }
                    widenedState.getStore().set(region, offset, value.getBitWidth(), new BasedNumberElement(
                            value.getRegion(), NumberElement.getTop(value.getBitWidth())));
                }
            }
        }
    }

    // Collect all values for all variables
    for (Map.Entry<RTLVariable, BasedNumberElement> entry : widenedState.getVariableValuation()) {
        eprec.varMap.put(entry.getKey(), entry.getValue());
    }

    // Collect all values for all memory areas
    PartitionedMemory<BasedNumberElement> store = widenedState.getStore();
    for (EntryIterator<MemoryRegion, Long, BasedNumberElement> entryIt = store.entryIterator(); entryIt
            .hasEntry(); entryIt.next()) {
        SetMultimap<Long, BasedNumberElement> memoryMap = eprec.regionMaps.get(entryIt.getLeftKey());
        if (memoryMap == null) {
            memoryMap = HashMultimap.create();
            eprec.regionMaps.put(entryIt.getLeftKey(), memoryMap);
        }
        memoryMap.put(entryIt.getRightKey(), entryIt.getValue());
    }

    // If it was changed, widenedState is now a new state
    return Pair.create((AbstractState) widenedState, precision);
}

From source file:com.puppycrawl.tools.checkstyle.checks.TranslationCheck.java

/**
 * Tests whether the given property files (arranged by their prefixes
 * in a Map) contain the proper keys.// www  .j ava 2s .  c  o m
 *
 * <p>Each group of files must have the same keys. If this is not the case
 * an error message is posted giving information which key misses in
 * which file.
 *
 * @param propFiles the property files organized as Map
 */
private void checkPropertyFileSets(SetMultimap<String, File> propFiles) {

    for (String key : propFiles.keySet()) {
        final Set<File> files = propFiles.get(key);

        if (files.size() >= 2) {
            // build a map from files to the keys they contain
            final Set<Object> keys = Sets.newHashSet();
            final SetMultimap<File, Object> fileMap = HashMultimap.create();

            for (File file : files) {
                final Set<Object> fileKeys = loadKeys(file);
                keys.addAll(fileKeys);
                fileMap.putAll(file, fileKeys);
            }

            // check the map for consistency
            compareKeySets(keys, fileMap);
        }
    }
}

From source file:com.google.copybara.doc.skylark.MarkdownGenerator.java

private void processDoc(SetMultimap<Class<? extends Annotation>, Element> elementsByAnnotation)
        throws ElementException, IOException {
    Multimap<String, String> docByElementType = ArrayListMultimap.create();

    for (Element element : elementsByAnnotation.get(SkylarkModule.class)) {
        TypeElement module = (TypeElement) element;
        StringBuilder sb = new StringBuilder();

        SkylarkModule skyModule = module.getAnnotation(SkylarkModule.class);
        if (!skyModule.documented()) {
            continue;
        }//  w w  w.  ja  va2s  .  co m
        sb.append("# ").append(skyModule.name()).append("\n\n");
        sb.append(skyModule.doc());
        sb.append("\n\n");

        // Generate flags associated with the whole module
        sb.append(generateFlagsInfo(module));

        for (Element member : module.getEnclosedElements()) {
            sb.append(generateFunctionDocumentation(module, skyModule, member));
        }
        docByElementType.put(skyModule.name(), sb.toString());
    }

    for (String group : docByElementType.keySet()) {
        FileObject resource = processingEnv.getFiler().createResource(StandardLocation.SOURCE_OUTPUT, "",
                group + ".copybara.md");

        try (Writer writer = resource.openWriter()) {
            for (String groupValues : docByElementType.get(group)) {
                writer.append(groupValues).append("\n");
            }
        }
    }
}