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

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

Introduction

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

Prototype

boolean putAll(@Nullable K key, Iterable<? extends V> values);

Source Link

Document

Stores a key-value pair in this multimap for each of values , all using the same key, key .

Usage

From source file:co.cask.cdap.internal.app.runtime.flow.FlowUtils.java

/**
 * Configures all queues being used in a flow.
 *
 * @return A Multimap from flowletId to QueueName where the flowlet is a consumer of.
 *///  w  w  w  .j av a2  s .  com
public static Multimap<String, QueueName> configureQueue(Program program, FlowSpecification flowSpec,
        StreamAdmin streamAdmin, QueueAdmin queueAdmin, TransactionExecutorFactory txExecutorFactory) {
    // Generate all queues specifications
    Id.Application appId = Id.Application.from(program.getNamespaceId(), program.getApplicationId());
    Table<QueueSpecificationGenerator.Node, String, Set<QueueSpecification>> queueSpecs = new SimpleQueueSpecificationGenerator(
            appId).create(flowSpec);

    // For each queue in the flow, gather all consumer groups information
    Multimap<QueueName, ConsumerGroupConfig> queueConfigs = HashMultimap.create();

    // Loop through each flowlet and generate the map from consumer flowlet id to queue
    ImmutableSetMultimap.Builder<String, QueueName> resultBuilder = ImmutableSetMultimap.builder();
    for (Map.Entry<String, FlowletDefinition> entry : flowSpec.getFlowlets().entrySet()) {
        String flowletId = entry.getKey();

        for (QueueSpecification queueSpec : Iterables.concat(queueSpecs.column(flowletId).values())) {
            resultBuilder.put(flowletId, queueSpec.getQueueName());
        }
    }

    // For each queue, gather all consumer groups.
    for (QueueSpecification queueSpec : Iterables.concat(queueSpecs.values())) {
        QueueName queueName = queueSpec.getQueueName();
        queueConfigs.putAll(queueName, getAllConsumerGroups(program, flowSpec, queueName, queueSpecs));
    }

    try {
        // Configure each stream consumer in the Flow. Also collects all queue configurers.
        final List<ConsumerGroupConfigurer> groupConfigurers = Lists.newArrayList();

        for (Map.Entry<QueueName, Collection<ConsumerGroupConfig>> entry : queueConfigs.asMap().entrySet()) {
            LOG.info("Queue config for {} : {}", entry.getKey(), entry.getValue());
            if (entry.getKey().isStream()) {
                Map<Long, Integer> configs = Maps.newHashMap();
                for (ConsumerGroupConfig config : entry.getValue()) {
                    configs.put(config.getGroupId(), config.getGroupSize());
                }
                streamAdmin.configureGroups(entry.getKey().toStreamId(), configs);
            } else {
                groupConfigurers.add(new ConsumerGroupConfigurer(queueAdmin.getQueueConfigurer(entry.getKey()),
                        entry.getValue()));
            }
        }

        // Configure queue transactionally
        try {
            Transactions.createTransactionExecutor(txExecutorFactory, groupConfigurers)
                    .execute(new TransactionExecutor.Subroutine() {
                        @Override
                        public void apply() throws Exception {
                            for (ConsumerGroupConfigurer configurer : groupConfigurers) {
                                configurer.configure();
                            }
                        }
                    });
        } finally {
            for (ConsumerGroupConfigurer configurer : groupConfigurers) {
                Closeables.closeQuietly(configurer);
            }
        }

        return resultBuilder.build();
    } catch (Exception e) {
        LOG.error("Failed to configure queues", e);
        throw Throwables.propagate(e);
    }
}

From source file:co.cask.cdap.internal.app.verification.FlowVerification.java

private <K, V> Multimap<K, V> toMultimap(Map<K, ? extends Collection<V>> map) {
    Multimap<K, V> result = HashMultimap.create();

    for (Map.Entry<K, ? extends Collection<V>> entry : map.entrySet()) {
        result.putAll(entry.getKey(), entry.getValue());
    }//  w ww . ja v  a2s. com
    return result;
}

From source file:com.kixeye.chassis.transport.websocket.WebSocketEnvelope.java

/**
 * Generates the header cache.//from  w ww  . j ava  2  s.c  o m
 */
private synchronized void generateHeaderCache() {
    if (headerCache != null) {
        // already generated cache
        return;
    }

    // generate the multimap
    Multimap<String, String> headers = HashMultimap.create();

    if (base.headers != null) {
        for (Header header : base.headers) {
            headers.putAll(header.name, header.value);
        }
    }

    headerCache = Multimaps.unmodifiableMultimap(headers);
}

From source file:org.apache.phoenix.hbase.index.write.recovery.PerRegionIndexWriteCache.java

/**
 * @param region//from   www.j av a 2  s.  c o  m
 * @param table
 * @param collection
 */
public void addEdits(Region region, HTableInterfaceReference table, Collection<Mutation> collection) {
    Multimap<HTableInterfaceReference, Mutation> edits = cache.get(region);
    if (edits == null) {
        edits = ArrayListMultimap.<HTableInterfaceReference, Mutation>create();
        cache.put(region, edits);
    }
    edits.putAll(table, collection);
}

From source file:org.apache.hadoop.hbase.index.write.recovery.PerRegionIndexWriteCache.java

/**
 * @param region/*  w  ww  . jav  a  2  s.c o m*/
 * @param table
 * @param collection
 */
public void addEdits(HRegion region, HTableInterfaceReference table, Collection<Mutation> collection) {
    Multimap<HTableInterfaceReference, Mutation> edits = cache.get(region);
    if (edits == null) {
        edits = ArrayListMultimap.<HTableInterfaceReference, Mutation>create();
        cache.put(region, edits);
    }
    edits.putAll(table, collection);
}

From source file:org.zalando.logbook.servlet.TeeResponse.java

@Override
public Multimap<String, String> getHeaders() {
    final Multimap<String, String> headers = ArrayListMultimap.create();

    for (final String header : getHeaderNames()) {
        headers.putAll(header, getHeaders(header));
    }/*from   w  w w . j  av a 2 s .c  o  m*/

    return headers;
}

From source file:org.apache.brooklyn.util.http.executor.apacheclient.HttpResponseWrapper.java

protected Multimap<String, String> headersImpl() {
    // The magic number "3" comes from ArrayListMultimap.DEFAULT_VALUES_PER_KEY
    if (headers == null) {
        Map<String, List<String>> headerLists = delegate.getHeaderLists();
        Multimap<String, String> headers = ArrayListMultimap.<String, String>create(headerLists.size(), 3);
        for (Map.Entry<String, List<String>> entry : headerLists.entrySet()) {
            headers.putAll(entry.getKey(), entry.getValue());
        }/*from   w  w w .  j  av  a 2 s  .  co  m*/
        this.headers = Multimaps.unmodifiableMultimap(headers);
    }
    return headers;
}

From source file:cc.kave.commons.utils.json.legacy.MultimapTypeAdapter.java

@Override
public Multimap deserialize(final JsonElement json, final Type typeOfT,
        final JsonDeserializationContext context) throws JsonParseException {
    final Multimap multimap = HashMultimap.create();
    final Map map = context.deserialize(json, createMapType(typeOfT));
    for (final Object key : map.keySet()) {
        final Collection values = (Collection) map.get(key);
        multimap.putAll(key, values);
    }/*from  w  w w  . jav a  2s.  com*/

    return multimap;
}

From source file:com.isotrol.impe3.freemarker.FreeMarker.java

/**
 * Returns the absolute URI to the requested page key. Query parameters in the request are included.
 *///from  w ww . j a va2 s  .c o  m
public static FreeMarkerFunction requestedPageAbsUri(final ComponentRequestContext context) {
    return new FreeMarkerFunction() {
        public Object apply(List<String> args) throws TemplateModelException {
            final Multimap<String, String> qp = LinkedListMultimap.create();
            final RequestParams rp = context.getRequestParams();
            for (String name : rp.getNames()) {
                qp.putAll(name, rp.get(name));
            }
            URI uri = context.getAbsoluteURI(context.getRoute(), qp);
            return returnUri(uri, args, 1);
        }
    };
}

From source file:com.dmdirc.ui.input.TabCompleter.java

/**
 * Attempts to complete the partial string.
 *
 * @param partial     The string to tab complete
 * @param additionals A list of additional strings to use
 *
 * @return A TabCompleterResult containing any matches found
 */// www .j  a va  2  s. c  om
public TabCompletionMatches complete(final String partial, @Nullable final AdditionalTabTargets additionals) {
    final TabCompletionMatches result = new TabCompletionMatches();

    final boolean caseSensitive = configManager.getOptionBool("tabcompletion", "casesensitive");
    final boolean allowEmpty = configManager.getOptionBool("tabcompletion", "allowempty");

    if (partial.isEmpty() && !allowEmpty) {
        return result;
    }

    final Multimap<TabCompletionType, String> targets = ArrayListMultimap.create(entries);
    if (additionals != null) {
        targets.putAll(TabCompletionType.ADDITIONAL, additionals);
    }

    targets.keys().stream()
            // Filter out keys that aren't allowed by the additional argument (if present)
            .filter(k -> additionals == null || additionals.shouldInclude(k))
            // Select all values for the valid keys
            .flatMap(k -> targets.get(k).stream())
            // Filter out values that don't case sensitively match, if case sensitivity is on
            .filter(v -> !caseSensitive || v.startsWith(partial))
            // Filter out values that don't case INsensitively match, if case sensitivity is off
            .filter(v -> caseSensitive || v.toLowerCase().startsWith(partial.toLowerCase()))
            // Filter out duplicates
            .distinct()
            // Add them all to the result
            .forEach(result::addResult);

    if (parent != null) {
        if (additionals != null) {
            additionals.clear();
        }

        result.merge(parent.complete(partial, additionals));
    }

    return result;
}