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

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

Introduction

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

Prototype

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

Source Link

Document

Because the values for a given key may have duplicates and follow the insertion ordering, this method returns a List , instead of the java.util.Collection specified in the Multimap interface.

Usage

From source file:com.android.ide.common.res2.AbstractResourceRepository.java

@Nullable
public List<ResourceItem> getResourceItem(@NonNull ResourceType resourceType, @NonNull String resourceName) {
    synchronized (ITEM_MAP_LOCK) {
        ListMultimap<String, ResourceItem> map = getMap(resourceType, false);

        if (map != null) {
            return map.get(resourceName);
        }/*from ww w  .  j  a va2s.co m*/
    }

    return null;
}

From source file:com.mgmtp.perfload.perfalyzer.reportpreparation.PerfMonReportPreparationStrategy.java

private void createCsvFiles(final File sourceDir, final File destDir,
        final ListMultimap<String, PerfAlyzerFile> byTypeAndHostMultimap) throws IOException {

    ListMultimap<String, String> globalContentListMultimap = LinkedListMultimap.create();
    StrTokenizer tokenizer = StrTokenizer.getCSVInstance();
    tokenizer.setDelimiterChar(DELIMITER);

    for (String key : byTypeAndHostMultimap.keySet()) {
        List<PerfAlyzerFile> filesByType = byTypeAndHostMultimap.get(key);
        File destFile = new File(destDir, key);

        String[] split = split(key, SystemUtils.FILE_SEPARATOR, 2);
        String host = split[0];//from  w  w w. jav  a  2  s  .  c  o  m
        String keyWithoutHost = split[1];

        List<String> contentList = newLinkedList();

        for (PerfAlyzerFile f : filesByType) {
            String type = f.getFileNameParts().get(1);

            // aggregated files always have two lines, a header and a data line
            List<String> lines = readLines(new File(sourceDir, f.getFile().getPath()), Charsets.UTF_8);
            if (lines.size() < 2) {
                // needs at least header and one content line
                continue;
            }
            if (contentList.isEmpty()) {
                // write header
                contentList.add(0, "\"type\"" + DELIMITER + lines.get(0));
            }
            String line = lines.get(1);
            tokenizer.reset(line);

            String[] columns = tokenizer.getTokenArray();

            StrBuilder sb = new StrBuilder(10 + line.length());
            appendEscapedAndQuoted(sb, DELIMITER, type);
            for (String column : columns) {
                appendEscapedAndQuoted(sb, DELIMITER, column);
            }

            line = sb.toString();
            contentList.add(line);

            List<String> globalContentList = globalContentListMultimap.get(keyWithoutHost);
            if (globalContentList.isEmpty()) {
                globalContentList.add("\"host\"" + DELIMITER + "\"type\"" + DELIMITER + lines.get(0));
            }
            globalContentList.add("\"" + host + "\"" + DELIMITER + line);
        }

        // exclude header line from sorting
        Collections.sort(contentList.subList(1, contentList.size()));

        writeLines(destFile, Charsets.UTF_8.name(), contentList);
    }

    for (String key : globalContentListMultimap.keySet()) {
        List<String> globalContentList = globalContentListMultimap.get(key);

        // exclude header line from sorting
        Collections.sort(globalContentList.subList(1, globalContentList.size()));

        writeLines(new File(destDir, "global" + SystemUtils.FILE_SEPARATOR + key), Charsets.UTF_8.name(),
                globalContentList);
    }
}

From source file:org.opendaylight.yangtools.yang.model.repo.util.AbstractSchemaRepository.java

@Override
public <T extends SchemaSourceRepresentation> CheckedFuture<T, SchemaSourceException> getSchemaSource(
        @Nonnull final SourceIdentifier id, @Nonnull final Class<T> representation) {
    final ArrayList<AbstractSchemaSourceRegistration<?>> sortedSchemaSourceRegistrations;

    synchronized (this) {
        final ListMultimap<Class<? extends SchemaSourceRepresentation>, AbstractSchemaSourceRegistration<?>> srcs = sources
                .get(id);/*from  w w w.jav  a  2s.co  m*/
        if (srcs == null) {
            return Futures.immediateFailedCheckedFuture(
                    new MissingSchemaSourceException("No providers registered for source" + id, id));
        }

        sortedSchemaSourceRegistrations = Lists.newArrayList(srcs.get(representation));
    }

    // TODO, remove and make sources keep sorted multimap (e.g. ArrayListMultimap with SortedLists)
    Collections.sort(sortedSchemaSourceRegistrations, SchemaProviderCostComparator.INSTANCE);

    final Iterator<AbstractSchemaSourceRegistration<?>> regs = sortedSchemaSourceRegistrations.iterator();
    if (!regs.hasNext()) {
        return Futures.immediateFailedCheckedFuture(new MissingSchemaSourceException(
                "No providers for source " + id + " representation " + representation + " available", id));
    }

    CheckedFuture<T, SchemaSourceException> fetchSourceFuture = fetchSource(id, regs);
    // Add callback to notify cache listeners about encountered schema
    Futures.addCallback(fetchSourceFuture, new FutureCallback<T>() {
        @Override
        public void onSuccess(final T result) {
            for (final SchemaListenerRegistration listener : listeners) {
                listener.getInstance().schemaSourceEncountered(result);
            }
        }

        @Override
        public void onFailure(@Nonnull final Throwable t) {
            LOG.trace("Skipping notification for encountered source {}, fetching source failed", id, t);
        }
    });

    return fetchSourceFuture;
}

From source file:eu.esdihumboldt.cst.functions.geometric.join.SpatialJoinHandler.java

/**
 * @see eu.esdihumboldt.hale.common.align.transformation.function.InstanceHandler#partitionInstances(eu.esdihumboldt.hale.common.instance.model.InstanceCollection,
 *      java.lang.String,//w ww  .  ja va2s . c om
 *      eu.esdihumboldt.hale.common.align.transformation.engine.TransformationEngine,
 *      com.google.common.collect.ListMultimap, java.util.Map,
 *      eu.esdihumboldt.hale.common.align.transformation.report.TransformationLog)
 */
@Override
public ResourceIterator<FamilyInstance> partitionInstances(InstanceCollection instances,
        String transformationIdentifier, TransformationEngine engine,
        ListMultimap<String, ParameterValue> transformationParameters, Map<String, String> executionParameters,
        TransformationLog log) throws TransformationException {

    if (transformationParameters == null || !transformationParameters.containsKey(PARAMETER_SPATIAL_JOIN)
            || transformationParameters.get(PARAMETER_SPATIAL_JOIN).isEmpty()) {
        throw new TransformationException("No join parameter defined");
    }

    if (services == null) {
        throw new IllegalStateException("ServiceProvider must be set before calling partitionInstances");
    }

    SpatialJoinParameter joinParameter = transformationParameters.get(PARAMETER_SPATIAL_JOIN).get(0)
            .as(SpatialJoinParameter.class);

    String validation = joinParameter.validate();
    if (validation != null) {
        throw new TransformationException("Spatial Join parameter invalid: " + validation);
    }

    List<TypeEntityDefinition> types = joinParameter.types;
    // ChildType -> DirectParentType
    int[] directParent = new int[joinParameter.types.size()];
    // ChildType -> (ParentType -> Collection<JoinCondition>)
    Map<Integer, Multimap<Integer, SpatialJoinCondition>> joinTable = new HashMap<>();

    for (SpatialJoinCondition condition : joinParameter.conditions) {
        int baseTypeIndex = types.indexOf(AlignmentUtil.getTypeEntity(condition.baseProperty));
        int joinTypeIndex = types.indexOf(AlignmentUtil.getTypeEntity(condition.joinProperty));
        Multimap<Integer, SpatialJoinCondition> typeTable = joinTable.get(joinTypeIndex);
        if (typeTable == null) {
            typeTable = ArrayListMultimap.create(2, 2);
            joinTable.put(joinTypeIndex, typeTable);
        }
        typeTable.put(baseTypeIndex, condition);

        // update highest type if necessary
        if (directParent[joinTypeIndex] < baseTypeIndex) {
            directParent[joinTypeIndex] = baseTypeIndex;
        }
    }

    // remember instances of first type to start join afterwards
    Collection<InstanceReference> startInstances = new LinkedList<InstanceReference>();

    // iterate once over all instances
    ResourceIterator<Instance> iterator = instances.iterator();
    try {
        while (iterator.hasNext()) {
            Instance next = iterator.next();

            // remember instances of first type
            if (next.getDefinition().equals(types.get(0).getDefinition())) {
                startInstances.add(instances.getReference(next));
            }
        }
    } finally {
        iterator.close();
    }

    return new SpatialJoinIterator(instances, startInstances, directParent, services, joinTable);
}

From source file:com.android.ide.common.res2.AbstractResourceRepository.java

/**
 * Returns true if this resource repository contains a resource of the given
 * name.//from  w ww .java2  s  .  c  om
 *
 * @param resourceType the type of resource to look up
 * @param resourceName the name of the resource
 * @return true if the resource is known
 */
public boolean hasResourceItem(@NonNull ResourceType resourceType, @NonNull String resourceName) {
    synchronized (ITEM_MAP_LOCK) {
        ListMultimap<String, ResourceItem> map = getMap(resourceType, false);

        if (map != null) {
            List<ResourceItem> itemList = map.get(resourceName);
            return itemList != null && !itemList.isEmpty();
        }
    }

    return false;
}

From source file:eu.esdihumboldt.cst.functions.numeric.MathematicalExpression.java

/**
 * @see AbstractSingleTargetPropertyTransformation#evaluate(String,
 *      TransformationEngine, ListMultimap, String,
 *      PropertyEntityDefinition, Map, TransformationLog)
 *//*  ww w  .  j  ava 2  s  . c  o m*/
@Override
protected Object evaluate(String transformationIdentifier, TransformationEngine engine,
        ListMultimap<String, PropertyValue> variables, String resultName,
        PropertyEntityDefinition resultProperty, Map<String, String> executionParameters, TransformationLog log)
        throws TransformationException {
    // get the mathematical expression
    String expression = getParameterChecked(PARAMETER_EXPRESSION).as(String.class);

    // replace transformation variables in expression
    expression = getExecutionContext().getVariables().replaceVariables(expression);

    List<PropertyValue> vars = variables.get(ENTITY_VARIABLE);

    try {
        return evaluateExpression(expression, vars);
    } catch (XExpression e) {
        throw new TransformationException("Error evaluating the cell expression", e);
    }
}

From source file:eu.esdihumboldt.hale.common.align.model.impl.mdexpl.MarkdownCellExplanation.java

private void addEntityBindings(Map<String, Object> binding, Set<? extends ParameterDefinition> definitions,
        ListMultimap<String, ? extends Entity> entities, String defaultName, boolean html, Locale locale) {
    if (!definitions.isEmpty()) {
        if (definitions.size() == 1) {
            // single entity
            ParameterDefinition def = definitions.iterator().next();

            // _defaultName always maps to single entity
            addEntityBindingValue(defaultName, def, entities.get(def.getName()), html, binding, locale);

            // in addition also the name if it is present
            String name = def.getName();
            if (name != null) {
                addEntityBindingValue(name, def, entities.get(name), html, binding, locale);
            }//from  ww w. j  a va  2 s  .  co m
        } else {
            for (ParameterDefinition def : definitions) {
                // add each entity based on its name, the default name is
                // used for the null entity
                String name = def.getName();
                if (name != null) {
                    addEntityBindingValue(name, def, entities.get(name), html, binding, locale);
                } else {
                    // null entity -> default name
                    addEntityBindingValue(defaultName, def, entities.get(name), html, binding, locale);
                }
            }
        }
    }
}

From source file:com.b2international.snowowl.core.compare.CompareResultsDsvExporter.java

public File export(IProgressMonitor monitor) throws IOException {

    CsvMapper mapper = new CsvMapper();
    CsvSchema schema = mapper.schemaFor(CompareData.class).withColumnSeparator(delimiter).withHeader().sortedBy(
            "componentType", "componentId", "componentType", "label", "changeKind", "attribute", "from", "to");

    try (SequenceWriter writer = mapper.writer(schema).writeValues(outputPath.toFile())) {
        monitor.beginTask("Exporting compare results to DSV", compareResults.getTotalNew()
                + compareResults.getTotalChanged() + compareResults.getTotalDeleted());

        ListMultimap<Short, ComponentIdentifier> newComponentIdentifiers = Multimaps
                .index(compareResults.getNewComponents(), ComponentIdentifier::getTerminologyComponentId);
        ListMultimap<Short, String> newComponentIds = ImmutableListMultimap.copyOf(
                Multimaps.transformValues(newComponentIdentifiers, ComponentIdentifier::getComponentId));

        for (short terminologyComponentId : newComponentIds.keySet()) {
            for (List<String> componentIds : Lists.partition(newComponentIds.get(terminologyComponentId),
                    PARTITION_SIZE)) {//from w w w .  j av a 2 s.  c o  m
                RevisionIndexRequestBuilder<CollectionResource<IComponent>> componentFetchRequest = fetcherFunction
                        .apply(terminologyComponentId, componentIds);

                if (componentFetchRequest == null) {
                    break;
                }

                CollectionResource<IComponent> components = componentFetchRequest
                        .build(repositoryUuid, compareBranch)
                        .execute(ApplicationContext.getServiceForClass(IEventBus.class)).getSync();

                for (IComponent component : components) {
                    writer.write(new CompareData(component, ChangeKind.ADDED));
                }

                monitor.worked(components.getItems().size());
            }
        }

        ListMultimap<Short, ComponentIdentifier> changedComponentIdentifiers = Multimaps
                .index(compareResults.getChangedComponents(), ComponentIdentifier::getTerminologyComponentId);
        ListMultimap<Short, String> changedComponentIds = ImmutableListMultimap.copyOf(
                Multimaps.transformValues(changedComponentIdentifiers, ComponentIdentifier::getComponentId));
        ListMultimap<String, IComponent> componentPairs = ArrayListMultimap.create(PARTITION_SIZE, 2);

        for (short terminologyComponentId : changedComponentIds.keySet()) {
            for (List<String> componentIds : Lists.partition(changedComponentIds.get(terminologyComponentId),
                    PARTITION_SIZE)) {
                componentPairs.clear();
                RevisionIndexRequestBuilder<CollectionResource<IComponent>> componentFetchRequest = fetcherFunction
                        .apply(terminologyComponentId, componentIds);

                if (componentFetchRequest == null) {
                    break;
                }

                componentFetchRequest.build(repositoryUuid, baseBranch)
                        .execute(ApplicationContext.getServiceForClass(IEventBus.class)).getSync()
                        .forEach(c -> componentPairs.put(c.getId(), c));

                componentFetchRequest.build(repositoryUuid, compareBranch)
                        .execute(ApplicationContext.getServiceForClass(IEventBus.class)).getSync()
                        .forEach(c -> componentPairs.put(c.getId(), c));

                for (Entry<String, List<IComponent>> entry : Multimaps.asMap(componentPairs).entrySet()) {
                    IComponent baseComponent = entry.getValue().get(0);
                    IComponent compareComponent = entry.getValue().get(1);
                    Collection<CompareData> compareResults = getCompareResultsOfComponent.apply(baseComponent,
                            compareComponent);

                    for (CompareData d : compareResults) {
                        writer.write(d);
                    }
                }

                monitor.worked(componentPairs.keySet().size());
            }
        }

        ListMultimap<Short, ComponentIdentifier> deletedComponentIdentifiers = Multimaps
                .index(compareResults.getDeletedComponents(), ComponentIdentifier::getTerminologyComponentId);
        ListMultimap<Short, String> deletedComponentIds = ImmutableListMultimap.copyOf(
                Multimaps.transformValues(deletedComponentIdentifiers, ComponentIdentifier::getComponentId));

        for (short terminologyComponentId : deletedComponentIds.keySet()) {
            for (List<String> componentIds : Lists.partition(deletedComponentIds.get(terminologyComponentId),
                    PARTITION_SIZE)) {
                RevisionIndexRequestBuilder<CollectionResource<IComponent>> componentFetchRequest = fetcherFunction
                        .apply(terminologyComponentId, componentIds);

                if (componentFetchRequest == null) {
                    break;
                }

                CollectionResource<IComponent> components = componentFetchRequest
                        .build(repositoryUuid, baseBranch)
                        .execute(ApplicationContext.getServiceForClass(IEventBus.class)).getSync();

                for (IComponent component : components) {
                    writer.write(new CompareData(component, ChangeKind.DELETED));
                }

                monitor.worked(components.getItems().size());
            }
        }

    } finally {
        monitor.done();
    }

    return outputPath.toFile();
}

From source file:org.apache.hadoop.hbase.rsgroup.RSGroupBasedLoadBalancer.java

@Override
public Map<ServerName, List<HRegionInfo>> roundRobinAssignment(List<HRegionInfo> regions,
        List<ServerName> servers) throws HBaseIOException {
    Map<ServerName, List<HRegionInfo>> assignments = Maps.newHashMap();
    ListMultimap<String, HRegionInfo> regionMap = ArrayListMultimap.create();
    ListMultimap<String, ServerName> serverMap = ArrayListMultimap.create();
    generateGroupMaps(regions, servers, regionMap, serverMap);
    for (String groupKey : regionMap.keySet()) {
        if (regionMap.get(groupKey).size() > 0) {
            Map<ServerName, List<HRegionInfo>> result = this.internalBalancer
                    .roundRobinAssignment(regionMap.get(groupKey), serverMap.get(groupKey));
            if (result != null) {
                assignments.putAll(result);
            }//  w  w w.  j  av a2 s. c om
        }
    }
    return assignments;
}

From source file:com.android.ide.common.res2.AbstractResourceRepository.java

@Nullable
public ResourceValue getConfiguredValue(@NonNull ResourceType type, @NonNull String name,
        @NonNull FolderConfiguration referenceConfig) {
    // get the resource item for the given type
    ListMultimap<String, ResourceItem> items = getMap(type, false);
    if (items == null) {
        return null;
    }//from  w  w w . j  av  a 2 s  . co m

    List<ResourceItem> keyItems = items.get(name);
    if (keyItems == null) {
        return null;
    }

    // look for the best match for the given configuration
    // the match has to be of type ResourceFile since that's what the input list contains
    ResourceItem match = (ResourceItem) referenceConfig.findMatchingConfigurable(keyItems);
    return match != null ? match.getResourceValue(mFramework) : null;
}