Example usage for com.google.common.collect ImmutableMultimap builder

List of usage examples for com.google.common.collect ImmutableMultimap builder

Introduction

In this page you can find the example usage for com.google.common.collect ImmutableMultimap builder.

Prototype

public static <K, V> Builder<K, V> builder() 

Source Link

Document

Returns a new builder.

Usage

From source file:com.spotify.heroic.ExtraParameters.java

public static ExtraParameters ofList(final List<String> input) {
    final ImmutableMultimap.Builder<String, String> result = ImmutableMultimap.builder();

    for (final String entry : input) {
        final int index = entry.indexOf('=');

        if (index < 0) {
            result.put(entry, "");
        } else {//w  w  w  . j  a v  a 2  s . c  o m
            result.put(entry.substring(0, index), entry.substring(index + 1));
        }
    }

    return new ExtraParameters(ImmutableList.of(), result.build());
}

From source file:org.immutables.value.processor.meta.Round.java

public Multimap<DeclaringPackage, ValueType> collectValues() {
    ImmutableList<Protoclass> protoclasses = collectProtoclasses();
    Map<DeclaringType, ValueType> enclosingTypes = Maps.newHashMap();

    ImmutableMultimap.Builder<DeclaringPackage, ValueType> builder = ImmutableMultimap.builder();

    // Collect enclosing
    for (Protoclass protoclass : protoclasses) {
        if (protoclass.kind().isEnclosing()) {
            ValueType type = composer().compose(protoclass);
            enclosingTypes.put(protoclass.declaringType().get(), type);
        }//  ww  w  .j  a  v a 2s  .  com
    }
    // Collect remaining and attach if nested
    for (Protoclass protoclass : protoclasses) {
        @Nullable
        ValueType current = null;
        if (protoclass.kind().isNested()) {
            @Nullable
            ValueType enclosing = enclosingTypes.get(protoclass.enclosingOf().get());
            if (enclosing != null) {
                current = composer().compose(protoclass);
                // Attach nested to enclosing
                enclosing.addNested(current);
            }
        }
        // getting the ValueType if it was alredy created and put into enclosingTypes
        if (current == null && protoclass.kind().isEnclosing()) {
            current = enclosingTypes.get(protoclass.declaringType().get());
        }
        // If none then we just create it
        if (current == null) {
            current = composer().compose(protoclass);
        }
        // We put all enclosing and nested values by the package
        builder.put(protoclass.packageOf(), current);
    }

    return builder.build();
}

From source file:com.github.rinde.rinsim.cli.Menu.java

Menu(Builder b) {
    header = b.header;/*www  .  jav  a 2 s. com*/
    footer = b.footer;
    cmdLineSyntax = b.cmdLineSyntax;
    optionMap = ImmutableMap.copyOf(b.optionMap);
    helpFormatter = b.helpFormatter;

    final ImmutableList.Builder<ImmutableSet<Option>> groupsBuilder = ImmutableList.builder();
    final ImmutableMultimap.Builder<Option, Option> groups2Builder = ImmutableMultimap.builder();
    for (final Set<Option> group : b.groups) {
        groupsBuilder.add(ImmutableSet.copyOf(group));
        for (final Option opt : group) {
            final Set<Option> groupWithoutMe = newLinkedHashSet(group);
            groupWithoutMe.remove(opt);
            groups2Builder.putAll(opt, groupWithoutMe);
        }
    }
    groups = groupsBuilder.build();
    groupMap = groups2Builder.build();
}

From source file:com.arpnetworking.metrics.mad.Bucket.java

/**
 * Close the bucket. The aggregates for each metric are emitted to the sink.
 *///from w  ww . j ava 2  s  .  c  om
public void close() {
    // Set the close flag before acquiring the write lock to allow "readers" to fail fast
    if (_isOpen.getAndSet(false)) {
        try {
            // Acquire the write lock and flush the calculated statistics
            _addCloseLock.writeLock().lock();
            final ImmutableMultimap.Builder<String, AggregatedData> data = ImmutableMultimap.builder();
            computeStatistics(_counterMetricCalculators, _specifiedCounterStatistics, data);
            computeStatistics(_gaugeMetricCalculators, _specifiedGaugeStatistics, data);
            computeStatistics(_timerMetricCalculators, _specifiedTimerStatistics, data);
            computeStatistics(_explicitMetricCalculators, _specifiedStatisticsCache, data);
            // TODO(vkoskela): Perform expression evaluation here. [NEXT]
            // -> This still requires realizing and indexing the computed aggregated data
            // in order to feed the expression evaluation. Once the filtering is consolidated
            // we can probably just build a map here and then do one copy into immutable form
            // in the PeriodicData. This becomes feasible with consolidated filtering because
            // fewer copies (e.g. none) are made downstream.
            // TODO(vkoskela): Perform alert evaluation here. [NEXT]
            // -> This requires expressions. Otherwise, it's just a matter of changing the
            // alerts abstraction from a Sink to something more appropriate and hooking it in
            // here.
            final PeriodicData periodicData = new PeriodicData.Builder().setData(data.build())
                    .setDimensions(_key).setPeriod(_period).setStart(_start).build();
            _sink.recordAggregateData(periodicData);
        } finally {
            _addCloseLock.writeLock().unlock();
        }
    } else {
        LOGGER.warn().setMessage("Bucket closed multiple times").addData("bucket", this).log();
    }
}

From source file:com.facebook.buck.apple.xcode.RuleDependencyFinder.java

/**
 * Create a map from targets to the tests that test them by examining
 * {@link com.facebook.buck.apple.IosTest#getSourceUnderTest()}.
 *//*from   www. j  av a 2 s  .  c  o m*/
private static ImmutableMultimap<BuildRule, BuildRule> buildRuleToTestRulesMap(PartialGraph graph) {
    ImmutableMultimap.Builder<BuildRule, BuildRule> ruleToTestRulesBuilder = ImmutableMultimap.builder();
    for (BuildTarget target : graph.getTargets()) {
        BuildRule rule = graph.getDependencyGraph().findBuildRuleByTarget(target);
        if (rule.getType().equals(IosTestDescription.TYPE)) {
            IosTest testBuildable = (IosTest) Preconditions.checkNotNull(rule.getBuildable());
            for (BuildRule sourceRule : testBuildable.getSourceUnderTest()) {
                ruleToTestRulesBuilder.put(sourceRule, rule);
            }
        }
    }
    return ruleToTestRulesBuilder.build();
}

From source file:org.jclouds.cloudwatch.options.ListMetricsOptions.java

/**
 * Returns a newly-created {@code ListMetricsOptions} based on the contents of
 * the {@code Builder}./* w  ww.j a  v a2  s.  c o  m*/
 */
@Override
public Multimap<String, String> buildFormParameters() {
    ImmutableMultimap.Builder<String, String> formParameters = ImmutableMultimap.<String, String>builder();
    int dimensionIndex = 1;

    // If namespace isn't specified, don't include it
    if (namespace != null) {
        formParameters.put("Namespace", namespace);
    }
    // If metricName isn't specified, don't include it
    if (metricName != null) {
        formParameters.put("MetricName", metricName);
    }

    // If dimensions isn't specified, don't include it
    if (dimensions != null) {
        for (Dimension dimension : dimensions) {
            formParameters.put("Dimensions.member." + dimensionIndex + ".Name", dimension.getName());
            formParameters.put("Dimensions.member." + dimensionIndex + ".Value", dimension.getValue());
            dimensionIndex++;
        }
    }

    // If afterMarker isn't specified, don't include it
    if (afterMarker != null) {
        formParameters.put("NextToken", afterMarker.toString());
    }

    return formParameters.build();
}

From source file:me.taylorkelly.mywarp.bukkit.commands.printer.AssetsPrinter.java

/**
 * Prints the given Limit to the receiver. The given Warps will be matched to the individual Limit.Types and displayed
 * accordingly.// www  .  ja va  2s. c  o  m
 *
 * @param receiver the Actor who is receiving this print
 * @param limit    the limit
 * @param warps    the Warps that are affected by the given Limit
 */
private void printLimit(Actor receiver, Limit limit, Collection<Warp> warps) {
    ImmutableMultimap.Builder<Limit.Type, Warp> builder = ImmutableMultimap.builder();

    // sort warps to types
    for (Warp warp : warps) {
        for (Limit.Type type : Limit.Type.values()) {
            if (type.getCondition().apply(warp)) {
                builder.put(type, warp);
            }
        }
    }

    // display...
    ImmutableMultimap<Limit.Type, Warp> index = builder.build();

    // ...the total limit
    receiver.sendMessage(ChatColor.GRAY
            + MESSAGES.getString("assets.total", CommandUtils.joinWorlds(limit.getAffectedWorlds()),
                    warpLimitCount(index.get(Limit.Type.TOTAL).size(), limit.getLimit(Limit.Type.TOTAL))));

    // ... all other limits
    List<String> limitStrings = new ArrayList<String>();
    for (Limit.Type type : DISPLAYABLE_TYPES) {
        Collection<Warp> privateWarps = index.get(type);

        limitStrings.add(ChatColor.GOLD
                + MESSAGES.getString("assets." + type.lowerCaseName(),
                        warpLimitCount(privateWarps.size(), limit.getLimit(type)))
                + " " + ChatColor.WHITE + ChatColor.ITALIC + CommandUtils.joinWarps(privateWarps));
    }

    receiver.sendMessage(FormattingUtils.toList(limitStrings));
}

From source file:org.prebake.core.GlobSet.java

/**
 * Returns a collection of globs grouped by path prefix.
 * A path prefix is a normalized path to a directory or file that is a
 * (non-strict) ancestor of all paths that match the glob.
 *///  w  ww.  j a v a  2 s.c  o  m
public Multimap<String, Glob> getGlobsGroupedByPrefix() {
    ImmutableMultimap.Builder<String, Glob> b = ImmutableMultimap.builder();
    groupByPrefixInto(prefixTree, b, new StringBuilder());
    return b.build();
}

From source file:foo.domaintest.http.HttpApiModule.java

@Provides
@Singleton/*  w  ww .  j av a2 s. c om*/
Multimap<String, String> provideParameterMap(@RequestData("queryString") String queryString,
        @RequestData("postBody") Lazy<String> lazyPostBody, @RequestData("charset") String requestCharset,
        FileItemIterator multipartIterator) {
    // Calling request.getParameter() or request.getParameterMap() etc. consumes the POST body. If
    // we got the "postpayload" param we don't want to parse the body, so use only the query params.
    // Note that specifying both "payload" and "postpayload" will result in the "payload" param
    // being honored and the POST body being completely ignored.
    ImmutableMultimap.Builder<String, String> params = new ImmutableMultimap.Builder<>();
    Multimap<String, String> getParams = parseQuery(queryString);
    params.putAll(getParams);
    if (getParams.containsKey("postpayload")) {
        // Treat the POST body as if it was the "payload" param.
        return params.put("payload", nullToEmpty(lazyPostBody.get())).build();
    }
    // No "postpayload" so it's safe to consume the POST body and look for params there.
    if (multipartIterator == null) { // Handle GETs and form-urlencoded POST requests.
        params.putAll(parseQuery(nullToEmpty(lazyPostBody.get())));
    } else { // Handle multipart/form-data requests.
        try {
            while (multipartIterator != null && multipartIterator.hasNext()) {
                FileItemStream item = multipartIterator.next();
                try (InputStream stream = item.openStream()) {
                    params.put(item.isFormField() ? item.getFieldName() : item.getName(),
                            CharStreams.toString(new InputStreamReader(stream, requestCharset)));
                }
            }
        } catch (FileUploadException | IOException e) {
            // Ignore the failure and fall through to return whatever params we managed to parse.
        }
    }
    return params.build();
}

From source file:org.jclouds.aws.util.AWSUtils.java

public static <R extends HttpRequest> R indexStringArrayToFormValuesWithStringFormat(R request, String format,
        Object input) {// w ww  .j  av a2 s .  c  om
    checkArgument(checkNotNull(input, "input") instanceof String[],
            "this binder is only valid for String[] : " + input.getClass());
    String[] values = (String[]) input;
    Builder<String, String> builder = ImmutableMultimap.builder();
    for (int i = 0; i < values.length; i++) {
        builder.put(String.format(format, i + 1),
                checkNotNull(values[i], format.toLowerCase() + "s[" + i + "]"));
    }
    ImmutableMultimap<String, String> forms = builder.build();
    return forms.size() == 0 ? request : (R) request.toBuilder().replaceFormParams(forms).build();
}