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

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

Introduction

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

Prototype

@Override
@SuppressWarnings("unchecked") 
public ImmutableMap<K, Collection<V>> asMap() 

Source Link

Document

Returns an immutable map that associates each key with its corresponding values in the multimap.

Usage

From source file:com.facebook.buck.java.intellij.IjModuleFactory.java

/**
 * Add the set of input paths to the {@link IjModule.Builder} as source folders.
 *
 * @param foldersToInputsIndex mapping of source folders to their inputs.
 * @param type folder type./* w  w  w.  j av a2s . c  o m*/
 * @param wantsPackagePrefix whether folders should be annotated with a package prefix. This
 *                           only makes sense when the source folder is Java source code.
 * @param context the module to add the folders to.
 */
private static void addSourceFolders(ImmutableMultimap<Path, Path> foldersToInputsIndex, IjFolder.Type type,
        boolean wantsPackagePrefix, ModuleBuildContext context) {
    for (Map.Entry<Path, Collection<Path>> entry : foldersToInputsIndex.asMap().entrySet()) {
        context.addSourceFolder(IjFolder.builder().setPath(entry.getKey())
                .setInputs(FluentIterable.from(entry.getValue()).toSortedSet(Ordering.natural())).setType(type)
                .setWantsPackagePrefix(wantsPackagePrefix).build());
    }
}

From source file:com.facebook.buck.jvm.java.intellij.IjModuleFactory.java

/**
 * Add the set of input paths to the {@link IjModule.Builder} as source folders.
 *
 * @param foldersToInputsIndex mapping of source folders to their inputs.
 * @param wantsPackagePrefix whether folders should be annotated with a package prefix. This
 *                           only makes sense when the source folder is Java source code.
 * @param context the module to add the folders to.
 *///from ww  w. ja va  2s.  c  o  m
private static void addSourceFolders(IJFolderFactory factory,
        ImmutableMultimap<Path, Path> foldersToInputsIndex, boolean wantsPackagePrefix,
        ModuleBuildContext context) {
    for (Map.Entry<Path, Collection<Path>> entry : foldersToInputsIndex.asMap().entrySet()) {
        context.addSourceFolder(factory.create(entry.getKey(), wantsPackagePrefix,
                ImmutableSortedSet.copyOf(Ordering.natural(), entry.getValue())));
    }
}

From source file:com.ning.arecibo.dashboard.resources.HostsStore.java

void cacheHosts(final ImmutableMultimap<String, Map<String, String>> newHostsInfo) {
    final String newBytes;
    try {//  www .  j a  v  a  2 s  .c o  m
        newBytes = mapper.writeValueAsString(newHostsInfo.asMap());
    } catch (IOException e) {
        log.warn("Unable to serialize new hosts", e);
        return;
    }

    synchronized (updateMonitor) {
        hostsInfo = newHostsInfo;
        etag = HASH.hashBytes(newBytes.getBytes(UTF_8)).toString();
        json = newBytes;
    }
}

From source file:com.facebook.buck.features.project.intellij.BaseIjModuleRule.java

protected void addResourceFolders(ResourceFolderFactory factory,
        ImmutableMultimap<Path, Path> foldersToInputsIndex, Path resourcesRoot, ModuleBuildContext context) {
    for (Map.Entry<Path, Collection<Path>> entry : foldersToInputsIndex.asMap().entrySet()) {
        context.addSourceFolder(factory.create(entry.getKey(), resourcesRoot,
                ImmutableSortedSet.copyOf(Ordering.natural(), entry.getValue())));
    }/*  www  .  j a va  2 s.c o m*/
}

From source file:com.facebook.buck.features.project.intellij.BaseIjModuleRule.java

/**
 * Add the set of input paths to the {@link IjModule.Builder} as source folders.
 *
 * @param foldersToInputsIndex mapping of source folders to their inputs.
 * @param wantsPackagePrefix whether folders should be annotated with a package prefix. This only
 *     makes sense when the source folder is Java source code.
 * @param context the module to add the folders to.
 *///from  ww w. jav a  2 s .  c o m
protected void addSourceFolders(IJFolderFactory factory, ImmutableMultimap<Path, Path> foldersToInputsIndex,
        boolean wantsPackagePrefix, ModuleBuildContext context) {
    for (Map.Entry<Path, Collection<Path>> entry : foldersToInputsIndex.asMap().entrySet()) {
        context.addSourceFolder(factory.create(entry.getKey(), wantsPackagePrefix,
                ImmutableSortedSet.copyOf(Ordering.natural(), entry.getValue())));
    }
}

From source file:com.google.devtools.build.lib.skyframe.serialization.ImmutableMultimapCodec.java

@Override
public void serialize(SerializationContext context, ImmutableMultimap<K, V> obj, CodedOutputStream codedOut)
        throws SerializationException, IOException {
    if (obj instanceof ImmutableListMultimap) {
        codedOut.writeBoolNoTag(true);/*from   w w  w . ja  va 2s. c o  m*/
    } else if (obj instanceof ImmutableSetMultimap) {
        codedOut.writeBoolNoTag(false);
    } else {
        throw new SerializationException("Unexpected multimap type: " + obj.getClass());
    }
    codedOut.writeInt32NoTag(obj.asMap().size());
    for (Map.Entry<K, Collection<V>> entry : obj.asMap().entrySet()) {
        context.serialize(entry.getKey(), codedOut);
        context.serialize(entry.getValue(), codedOut);
    }
}

From source file:com.google.devtools.build.lib.query2.output.ProtoOutputFormatter.java

/** Converts a logical {@link Target} object into a {@link Build.Target} protobuffer. */
@VisibleForTesting//from w ww  .  j  a v a2 s. co  m
public Build.Target toTargetProtoBuffer(Target target) throws InterruptedException {
    Build.Target.Builder targetPb = Build.Target.newBuilder();

    String location = getLocation(target, relativeLocations);
    if (target instanceof Rule) {
        Rule rule = (Rule) target;
        Build.Rule.Builder rulePb = Build.Rule.newBuilder().setName(rule.getLabel().toString())
                .setRuleClass(rule.getRuleClass());
        if (includeLocation()) {
            rulePb.setLocation(location);
        }
        Map<Attribute, Build.Attribute> serializedAttributes = Maps.newHashMap();
        for (Attribute attr : rule.getAttributes()) {
            if ((!includeDefaultValues && !rule.isAttributeValueExplicitlySpecified(attr))
                    || !includeAttribute(rule, attr)) {
                continue;
            }
            Object flattenedAttributeValue = flattenAttributeValues(attr.getType(),
                    getPossibleAttributeValues(rule, attr));
            Build.Attribute serializedAttribute = AttributeFormatter.getAttributeProto(attr,
                    flattenedAttributeValue, rule.isAttributeValueExplicitlySpecified(attr),
                    /*encodeBooleanAndTriStateAsIntegerAndString=*/ true);
            rulePb.addAttribute(serializedAttribute);
            serializedAttributes.put(attr, serializedAttribute);
        }

        postProcess(rule, rulePb, serializedAttributes);

        Environment env = rule.getRuleClassObject().getRuleDefinitionEnvironment();
        if (env != null && includeRuleDefinitionEnvironment()) {
            // The RuleDefinitionEnvironment is always defined for Skylark rules and
            // always null for non Skylark rules.
            rulePb.addAttribute(Build.Attribute.newBuilder().setName(RULE_IMPLEMENTATION_HASH_ATTR_NAME)
                    .setType(ProtoUtils.getDiscriminatorFromType(Type.STRING))
                    .setStringValue(env.getTransitiveContentHashCode()));
        }

        ImmutableMultimap<Attribute, Label> aspectsDependencies = aspectResolver
                .computeAspectDependencies(target, dependencyFilter);
        // Add information about additional attributes from aspects.
        for (Entry<Attribute, Collection<Label>> entry : aspectsDependencies.asMap().entrySet()) {
            Attribute attribute = entry.getKey();
            Collection<Label> labels = entry.getValue();
            if (!includeAspectAttribute(attribute, labels)) {
                continue;
            }
            Object attributeValue = getAspectAttributeValue(attribute, labels);
            Build.Attribute serializedAttribute = AttributeFormatter.getAttributeProto(attribute,
                    attributeValue, /*explicitlySpecified=*/ false,
                    /*encodeBooleanAndTriStateAsIntegerAndString=*/ true);
            rulePb.addAttribute(serializedAttribute);
        }
        if (includeRuleInputsAndOutputs()) {
            // Add all deps from aspects as rule inputs of current target.
            for (Label label : aspectsDependencies.values()) {
                rulePb.addRuleInput(label.toString());
            }

            // Include explicit elements for all direct inputs and outputs of a rule;
            // this goes beyond what is available from the attributes above, since it
            // may also (depending on options) include implicit outputs,
            // host-configuration outputs, and default values.
            for (Label label : rule.getLabels(dependencyFilter)) {
                rulePb.addRuleInput(label.toString());
            }
            for (OutputFile outputFile : rule.getOutputFiles()) {
                Label fileLabel = outputFile.getLabel();
                rulePb.addRuleOutput(fileLabel.toString());
            }
        }
        for (String feature : rule.getFeatures()) {
            rulePb.addDefaultSetting(feature);
        }

        targetPb.setType(RULE);
        targetPb.setRule(rulePb);
    } else if (target instanceof OutputFile) {
        OutputFile outputFile = (OutputFile) target;
        Label label = outputFile.getLabel();

        Rule generatingRule = outputFile.getGeneratingRule();
        GeneratedFile.Builder output = GeneratedFile.newBuilder()
                .setGeneratingRule(generatingRule.getLabel().toString()).setName(label.toString());

        if (includeLocation()) {
            output.setLocation(location);
        }
        targetPb.setType(GENERATED_FILE);
        targetPb.setGeneratedFile(output.build());
    } else if (target instanceof InputFile) {
        InputFile inputFile = (InputFile) target;
        Label label = inputFile.getLabel();

        Build.SourceFile.Builder input = Build.SourceFile.newBuilder().setName(label.toString());

        if (includeLocation()) {
            input.setLocation(location);
        }

        if (inputFile.getName().equals("BUILD")) {
            Set<Label> subincludeLabels = new LinkedHashSet<>();
            subincludeLabels.addAll(aspectResolver == null ? inputFile.getPackage().getSubincludeLabels()
                    : aspectResolver.computeBuildFileDependencies(inputFile.getPackage(),
                            BuildFileDependencyMode.SUBINCLUDE));
            subincludeLabels.addAll(aspectResolver == null ? inputFile.getPackage().getSkylarkFileDependencies()
                    : aspectResolver.computeBuildFileDependencies(inputFile.getPackage(),
                            BuildFileDependencyMode.SKYLARK));

            for (Label skylarkFileDep : subincludeLabels) {
                input.addSubinclude(skylarkFileDep.toString());
            }

            for (String feature : inputFile.getPackage().getFeatures()) {
                input.addFeature(feature);
            }

            input.setPackageContainsErrors(inputFile.getPackage().containsErrors());
        }

        for (Label visibilityDependency : target.getVisibility().getDependencyLabels()) {
            input.addPackageGroup(visibilityDependency.toString());
        }

        for (Label visibilityDeclaration : target.getVisibility().getDeclaredLabels()) {
            input.addVisibilityLabel(visibilityDeclaration.toString());
        }

        targetPb.setType(SOURCE_FILE);
        targetPb.setSourceFile(input);
    } else if (target instanceof FakeSubincludeTarget) {
        Label label = target.getLabel();
        SourceFile.Builder input = SourceFile.newBuilder().setName(label.toString());

        if (includeLocation()) {
            input.setLocation(location);
        }
        targetPb.setType(SOURCE_FILE);
        targetPb.setSourceFile(input.build());
    } else if (target instanceof PackageGroup) {
        PackageGroup packageGroup = (PackageGroup) target;
        Build.PackageGroup.Builder packageGroupPb = Build.PackageGroup.newBuilder()
                .setName(packageGroup.getLabel().toString());
        for (String containedPackage : packageGroup.getContainedPackages()) {
            packageGroupPb.addContainedPackage(containedPackage);
        }
        for (Label include : packageGroup.getIncludes()) {
            packageGroupPb.addIncludedPackageGroup(include.toString());
        }

        targetPb.setType(PACKAGE_GROUP);
        targetPb.setPackageGroup(packageGroupPb);
    } else if (target instanceof EnvironmentGroup) {
        EnvironmentGroup envGroup = (EnvironmentGroup) target;
        Build.EnvironmentGroup.Builder envGroupPb = Build.EnvironmentGroup.newBuilder()
                .setName(envGroup.getLabel().toString());
        for (Label env : envGroup.getEnvironments()) {
            envGroupPb.addEnvironment(env.toString());
        }
        for (Label defaultEnv : envGroup.getDefaults()) {
            envGroupPb.addDefault(defaultEnv.toString());
        }
        targetPb.setType(ENVIRONMENT_GROUP);
        targetPb.setEnvironmentGroup(envGroupPb);
    } else {
        throw new IllegalArgumentException(target.toString());
    }

    return targetPb.build();
}

From source file:org.apache.aurora.common.args.ArgScanner.java

/**
 * Applies argument values to fields based on their annotations.
 *
 * @param parserOracle ParserOracle available to parse raw args with.
 * @param verifiers Verifiers available to verify argument constraints with.
 * @param argsInfo Fields to apply argument values to.
 * @param args Unparsed argument values.
 * @param positionalArgs The unparsed positional arguments.
 * @return {@code true} if the given {@code args} were successfully applied to their
 *     corresponding {@link Arg} fields.
 *///from w  w  w .j a v a2  s .co m
private boolean process(final ParserOracle parserOracle, Verifiers verifiers, ArgsInfo argsInfo,
        Map<String, String> args, List<String> positionalArgs) {

    if (!Sets.intersection(args.keySet(), ArgumentInfo.HELP_ARGS).isEmpty()) {
        printHelp(verifiers, argsInfo);
        return false;
    }

    Iterable<? extends OptionInfo<?>> optionInfos = argsInfo.getOptionInfos();

    final Set<String> argsFailedToParse = Sets.newHashSet();
    final Set<String> argsConstraintsFailed = Sets.newHashSet();

    Set<String> argAllShortNamesNoCollisions = getNoCollisions(optionInfos);

    final Map<String, OptionInfo<?>> argsByName = ImmutableMap.<String, OptionInfo<?>>builder()
            // Map by short arg name -> arg def.
            .putAll(Maps.uniqueIndex(Iterables.filter(optionInfos,
                    Predicates.compose(Predicates.in(argAllShortNamesNoCollisions), GET_OPTION_INFO_NAME)),
                    GET_OPTION_INFO_NAME))
            // Map by negated short arg name (for booleans)
            .putAll(Maps
                    .uniqueIndex(
                            Iterables.filter(Iterables.filter(optionInfos, IS_BOOLEAN),
                                    Predicates.compose(Predicates.in(argAllShortNamesNoCollisions),
                                            GET_OPTION_INFO_NEGATED_NAME)),
                            GET_OPTION_INFO_NEGATED_NAME))
            .build();

    // TODO(William Farner): Make sure to disallow duplicate arg specification by short and
    // canonical names.

    // TODO(William Farner): Support non-atomic argument constraints.  @OnlyIfSet, @OnlyIfNotSet,
    //    @ExclusiveOf to define inter-argument constraints.

    Set<String> recognizedArgs = Sets.intersection(argsByName.keySet(), args.keySet());

    for (String argName : recognizedArgs) {
        String argValue = args.get(argName);
        OptionInfo<?> optionInfo = argsByName.get(argName);

        try {
            optionInfo.load(parserOracle, argName, argValue);
        } catch (IllegalArgumentException e) {
            argsFailedToParse.add(argName + " - " + e.getMessage());
        }
    }

    Set<String> commandLineArgumentInfos = Sets.newTreeSet();

    Iterable<? extends ArgumentInfo<?>> allArguments = argsInfo.getOptionInfos();

    for (ArgumentInfo<?> anArgumentInfo : allArguments) {
        Arg<?> arg = anArgumentInfo.getArg();

        commandLineArgumentInfos.add(String.format("%s: %s", anArgumentInfo.getName(), arg.uncheckedGet()));

        try {
            anArgumentInfo.verify(verifiers);
        } catch (IllegalArgumentException e) {
            argsConstraintsFailed.add(anArgumentInfo.getName() + " - " + e.getMessage());
        }
    }

    ImmutableMultimap<String, String> warningMessages = ImmutableMultimap.<String, String>builder()
            .putAll("Unrecognized arguments", Sets.difference(args.keySet(), argsByName.keySet()))
            .putAll("Failed to parse", argsFailedToParse)
            .putAll("Value did not meet constraints", argsConstraintsFailed).build();

    if (!warningMessages.isEmpty()) {
        printHelp(verifiers, argsInfo);
        StringBuilder sb = new StringBuilder();
        for (Map.Entry<String, Collection<String>> warnings : warningMessages.asMap().entrySet()) {
            sb.append(warnings.getKey()).append(":\n\t").append(Joiner.on("\n\t").join(warnings.getValue()))
                    .append("\n");
        }
        throw new IllegalArgumentException(sb.toString());
    }

    LOG.info("-------------------------------------------------------------------------");
    LOG.info("Command line argument values");
    for (String commandLineArgumentInfo : commandLineArgumentInfos) {
        LOG.info(commandLineArgumentInfo);
    }
    LOG.info("-------------------------------------------------------------------------");
    return true;
}

From source file:com.twitter.common.args.ArgScanner.java

/**
 * Applies argument values to fields based on their annotations.
 *
 * @param parserOracle ParserOracle available to parse raw args with.
 * @param verifiers Verifiers available to verify argument constraints with.
 * @param argsInfo Fields to apply argument values to.
 * @param args Unparsed argument values.
 * @param positionalArgs The unparsed positional arguments.
 * @return {@code true} if the given {@code args} were successfully applied to their
 *     corresponding {@link com.twitter.common.args.Arg} fields.
 *//* ww  w  .ja  v a2s .co m*/
private boolean process(final ParserOracle parserOracle, Verifiers verifiers, ArgsInfo argsInfo,
        Map<String, String> args, List<String> positionalArgs) {

    if (!Sets.intersection(args.keySet(), ArgumentInfo.HELP_ARGS).isEmpty()) {
        printHelp(verifiers, argsInfo);
        return false;
    }

    Optional<? extends PositionalInfo<?>> positionalInfoOptional = argsInfo.getPositionalInfo();
    checkArgument(positionalInfoOptional.isPresent() || positionalArgs.isEmpty(),
            "Positional arguments have been supplied but there is no Arg annotated to received them.");

    Iterable<? extends OptionInfo<?>> optionInfos = argsInfo.getOptionInfos();

    final Set<String> argsFailedToParse = Sets.newHashSet();
    final Set<String> argsConstraintsFailed = Sets.newHashSet();

    Set<String> argAllShortNamesNoCollisions = getNoCollisions(optionInfos);

    final Map<String, OptionInfo<?>> argsByName = ImmutableMap.<String, OptionInfo<?>>builder()
            // Map by short arg name -> arg def.
            .putAll(Maps.uniqueIndex(Iterables.filter(optionInfos,
                    Predicates.compose(Predicates.in(argAllShortNamesNoCollisions), GET_OPTION_INFO_NAME)),
                    GET_OPTION_INFO_NAME))
            // Map by canonical arg name -> arg def.
            .putAll(Maps.uniqueIndex(optionInfos, GET_CANONICAL_ARG_NAME))
            // Map by negated short arg name (for booleans)
            .putAll(Maps.uniqueIndex(Iterables.filter(Iterables.filter(optionInfos, IS_BOOLEAN),
                    Predicates.compose(Predicates.in(argAllShortNamesNoCollisions),
                            GET_OPTION_INFO_NEGATED_NAME)),
                    GET_OPTION_INFO_NEGATED_NAME))
            // Map by negated canonical arg name (for booleans)
            .putAll(Maps.uniqueIndex(Iterables.filter(optionInfos, IS_BOOLEAN), GET_CANONICAL_NEGATED_ARG_NAME))
            .build();

    // TODO(William Farner): Make sure to disallow duplicate arg specification by short and
    // canonical names.

    // TODO(William Farner): Support non-atomic argument constraints.  @OnlyIfSet, @OnlyIfNotSet,
    //    @ExclusiveOf to define inter-argument constraints.

    Set<String> recognizedArgs = Sets.intersection(argsByName.keySet(), args.keySet());

    for (String argName : recognizedArgs) {
        String argValue = args.get(argName);
        OptionInfo<?> optionInfo = argsByName.get(argName);

        try {
            optionInfo.load(parserOracle, argName, argValue);
        } catch (IllegalArgumentException e) {
            argsFailedToParse.add(argName + " - " + e.getMessage());
        }
    }

    if (positionalInfoOptional.isPresent()) {
        PositionalInfo<?> positionalInfo = positionalInfoOptional.get();
        positionalInfo.load(parserOracle, positionalArgs);
    }

    Set<String> commandLineArgumentInfos = Sets.newTreeSet();

    Iterable<? extends ArgumentInfo<?>> allArguments = argsInfo.getOptionInfos();

    if (positionalInfoOptional.isPresent()) {
        PositionalInfo<?> positionalInfo = positionalInfoOptional.get();
        allArguments = Iterables.concat(optionInfos, ImmutableList.of(positionalInfo));
    }

    for (ArgumentInfo<?> anArgumentInfo : allArguments) {
        Arg<?> arg = anArgumentInfo.getArg();

        commandLineArgumentInfos.add(String.format("%s (%s): %s", anArgumentInfo.getName(),
                anArgumentInfo.getCanonicalName(), arg.uncheckedGet()));

        try {
            anArgumentInfo.verify(verifiers);
        } catch (IllegalArgumentException e) {
            argsConstraintsFailed.add(anArgumentInfo.getName() + " - " + e.getMessage());
        }
    }

    ImmutableMultimap<String, String> warningMessages = ImmutableMultimap.<String, String>builder()
            .putAll("Unrecognized arguments", Sets.difference(args.keySet(), argsByName.keySet()))
            .putAll("Failed to parse", argsFailedToParse)
            .putAll("Value did not meet constraints", argsConstraintsFailed).build();

    if (!warningMessages.isEmpty()) {
        printHelp(verifiers, argsInfo);
        StringBuilder sb = new StringBuilder();
        for (Map.Entry<String, Collection<String>> warnings : warningMessages.asMap().entrySet()) {
            sb.append(warnings.getKey()).append(":\n\t").append(Joiner.on("\n\t").join(warnings.getValue()))
                    .append("\n");
        }
        throw new IllegalArgumentException(sb.toString());
    }

    LOG.info("-------------------------------------------------------------------------");
    LOG.info("Command line argument values");
    for (String commandLineArgumentInfo : commandLineArgumentInfos) {
        LOG.info(commandLineArgumentInfo);
    }
    LOG.info("-------------------------------------------------------------------------");
    return true;
}