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.spectralogic.ds3client.commands.interfaces.RequestHeadersImpl.java

/**
 * Retrieves the percent-encoded multimap. Used in {@link NetworkClientImpl}
 *//*w ww .j ava  2  s  .c om*/
@Override
public Multimap<String, String> getMultimap() {
    final ImmutableMultimap.Builder<String, String> builder = ImmutableMultimap.builder();
    builder.putAll(headers);
    return builder.build();
}

From source file:org.gradle.internal.fingerprint.impl.DefaultCurrentFileCollectionFingerprint.java

private DefaultCurrentFileCollectionFingerprint(Map<String, FileSystemLocationFingerprint> fingerprints,
        FingerprintCompareStrategy compareStrategy, FingerprintingStrategy.Identifier identifier,
        Iterable<FileSystemSnapshot> roots) {
    this.fingerprints = fingerprints;
    this.compareStrategy = compareStrategy;
    this.identifier = identifier;
    this.roots = roots;

    final ImmutableMultimap.Builder<String, HashCode> builder = ImmutableMultimap.builder();
    accept(new FileSystemSnapshotVisitor() {
        @Override/* w w w  . j  a v  a 2 s.c  o  m*/
        public boolean preVisitDirectory(DirectorySnapshot directorySnapshot) {
            builder.put(directorySnapshot.getAbsolutePath(), directorySnapshot.getHash());
            return false;
        }

        @Override
        public void visit(FileSystemLocationSnapshot fileSnapshot) {
            builder.put(fileSnapshot.getAbsolutePath(), fileSnapshot.getHash());
        }

        @Override
        public void postVisitDirectory(DirectorySnapshot directorySnapshot) {
        }
    });
    this.rootHashes = builder.build();
}

From source file:com.exoplatform.iversion.Merge.java

public <M, T extends Version<K, V, M>> Merge(Iterable<VersionNode<K, V, M, T>> versions) {
    checkNotNull(versions, "versions");
    Iterator<VersionNode<K, V, M, T>> iter = versions.iterator();

    // No versions
    if (!iter.hasNext()) {
        mergedProperties = ImmutableMap.of();
        revisions = ImmutableSet.of();/* w ww  .j  a v  a 2 s  . c o  m*/
        conflicts = ImmutableMultimap.of();
    } else {
        VersionNode<K, V, M, T> versionNode = next(iter);

        // One version
        if (!iter.hasNext()) {
            mergedProperties = versionNode.getProperties();
            revisions = ImmutableSet.of(versionNode.getRevision());
            conflicts = ImmutableMultimap.of();
        }
        // More than one version -> merge!
        else {
            Map<K, VersionProperty<V>> mergedProperties = Maps.newLinkedHashMap(versionNode.getProperties());
            Set<Long> heads = Sets.newHashSet(versionNode.getRevision());
            ImmutableMultimap.Builder<K, VersionProperty<V>> conflicts = ImmutableMultimap.builder();

            Set<Long> mergedRevisions = Sets.newHashSet(versionNode.getRevisions());
            do {
                versionNode = next(iter);

                // Version already merged?
                if (!mergedRevisions.contains(versionNode.getRevision())) {
                    for (Map.Entry<K, VersionProperty<V>> entry : versionNode.getProperties().entrySet()) {
                        K key = entry.getKey();
                        VersionProperty<V> nextValue = entry.getValue();

                        // nextValue derives from common ancestor?
                        if (!mergedRevisions.contains(nextValue.revision)) {
                            VersionProperty<V> previousValue = mergedProperties.get(key);

                            // New value
                            if (previousValue == null) {
                                mergedProperties.put(key, nextValue);
                            }
                            // Conflicting value?
                            else if (!equal(previousValue.value, nextValue.value)) {
                                conflicts.put(key, nextValue);
                            }
                        }
                    }
                    mergedRevisions.addAll(versionNode.getRevisions());

                    heads.removeAll(versionNode.getRevisions());
                    heads.add(versionNode.getRevision());
                }
            } while (iter.hasNext());

            this.mergedProperties = unmodifiableMap(mergedProperties);
            this.revisions = unmodifiableSet(heads);
            this.conflicts = conflicts.build();
        }
    }

}

From source file:com.google.caliper.runner.EnvironmentGetter.java

/**
 * Returns the key/value pairs from the specified properties-file like file.
 * Unlike standard Java properties files, {@code reader} is allowed to list
 * the same property multiple times. Comments etc. are unsupported.
 *
 * <p>If there's any problem reading the file's contents, we'll return an
 * empty Multimap./*from  ww w.  jav a 2 s  .co m*/
 */
private static Multimap<String, String> propertiesFromLinuxFile(String file) {
    try {
        List<String> lines = Files.readLines(new File(file), Charset.defaultCharset());
        ImmutableMultimap.Builder<String, String> result = ImmutableMultimap.builder();
        for (String line : lines) {
            // TODO(schmoe): replace with Splitter (in Guava release 10)
            String[] parts = line.split("\\s*\\:\\s*", 2);
            if (parts.length == 2) {
                result.put(parts[0], parts[1]);
            }
        }
        return result.build();
    } catch (IOException e) {
        // If there's any problem reading the file, just return an empty multimap.
        return ImmutableMultimap.of();
    }
}

From source file:org.auraframework.impl.css.token.TokenCacheImpl.java

public TokenCacheImpl(DefinitionService definitionService, Iterable<DefDescriptor<TokensDef>> descriptors)
        throws QuickFixException {
    checkNotNull(descriptors, "descriptors cannot be null, see EmptyTokenCache instead");
    this.definitionService = definitionService;

    // we want a unique list of the concrete descs. Since last one wins, there's no need to include duplicate
    // entries; just the last one. duplicate entries could come from descriptor providers that resolve to the
    // same descriptor, or just user error/inefficiency
    Set<DefDescriptor<TokensDef>> unique = new LinkedHashSet<>();

    // in the case of descriptor providers, maintain a mapping to the original descriptor(s)
    ImmutableMultimap.Builder<DefDescriptor<TokensDef>, DefDescriptor<TokensDef>> origs = ImmutableMultimap
            .builder();/* www  . j a  va2 s.  co m*/

    for (DefDescriptor<TokensDef> descriptor : descriptors) {
        DefDescriptor<TokensDef> concrete = definitionService.getDefinition(descriptor).getConcreteDescriptor();
        unique.remove(concrete); // unlike the normal behavior, we want to move the position of duplicate entries
        unique.add(concrete);
        if (descriptor != concrete) {
            origs.put(concrete, descriptor);
        }
    }

    this.originals = origs.build();
    this.descriptors = ImmutableList.copyOf(unique);
    this.reversed = this.descriptors.reverse();

    ImmutableTable.Builder<String, DefDescriptor<TokensDef>, String> table = ImmutableTable.builder();
    for (DefDescriptor<TokensDef> descriptor : this.descriptors) { // iterate through the unique list
        TokensDef def = definitionService.getDefinition(descriptor);
        if (def.getMapProvider() != null) {
            TokenMapProviderDef tokenMapProviderDef = definitionService.getDefinition(def.getMapProvider());
            TokenMapProviderInstance instance = Aura.getInstanceService().getInstance(tokenMapProviderDef);
            Map<String, String> map = instance.provide();
            for (Entry<String, String> entry : map.entrySet()) {
                table.put(entry.getKey(), descriptor, entry.getValue());
            }
        }
    }
    this.dynamicTokens = table.build();
}

From source file:org.apache.gobblin.config.common.impl.InMemoryTopology.java

private synchronized void computeImportedByMap(Optional<Config> runtimeConfig) {
    if (this.fullImportedByMap != null) {
        return;/*from w ww  .j a v a2 s . c o  m*/
    }

    ImmutableMultimap.Builder<ConfigKeyPath, ConfigKeyPath> importedByBuilder = ImmutableMultimap.builder();

    // breath first search the whole topology to build ownImports map and ownImportedByMap
    // calls to retrieve cache / set cache if not present
    Collection<ConfigKeyPath> currentLevel = this.getChildren(SingleLinkedListConfigKeyPath.ROOT);

    List<ConfigKeyPath> rootImports = this.getOwnImports(SingleLinkedListConfigKeyPath.ROOT, runtimeConfig);
    Preconditions.checkArgument(rootImports == null || rootImports.size() == 0,
            "Root can not import other nodes, otherwise circular dependency will happen");

    while (!currentLevel.isEmpty()) {
        Collection<ConfigKeyPath> nextLevel = new ArrayList<>();
        for (ConfigKeyPath configKeyPath : currentLevel) {
            // calls to retrieve cache / set cache if not present
            List<ConfigKeyPath> ownImports = this.getOwnImports(configKeyPath, runtimeConfig);
            this.ownImportMap.put(configKeyPath, ownImports);
            for (ConfigKeyPath importedPath : ownImports) {
                importedByBuilder.put(importedPath, configKeyPath);
            }

            // calls to retrieve cache / set cache if not present
            Collection<ConfigKeyPath> tmp = this.getChildren(configKeyPath);
            nextLevel.addAll(tmp);
        }
        currentLevel = nextLevel;
    }

    this.fullImportedByMap = importedByBuilder.build();
}

From source file:org.openqa.selenium.grid.server.ServletRequestWrappingHttpRequest.java

private Map<String, Collection<String>> parseQueryString() {
    String queryString = req.getQueryString();
    if (queryString == null || queryString.isEmpty()) {
        return ImmutableMap.of();
    }/*from   w  w  w .  j  a  va 2s  .c om*/

    ImmutableMultimap.Builder<String, String> allParams = ImmutableMultimap.builder();

    Iterable<String> paramsAndValues = Splitter.on("&").split(queryString);
    for (String paramAndValue : paramsAndValues) {
        int index = paramAndValue.indexOf("=");

        String key;
        String value;
        if (index == -1) {
            key = paramAndValue;
            value = "";
        } else {
            key = paramAndValue.substring(0, index);
            if (paramAndValue.length() >= index) {
                value = paramAndValue.substring(index + 1);
            } else {
                value = "";
            }
        }

        try {
            allParams.put(URLDecoder.decode(key, "UTF-8"), URLDecoder.decode(value, "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            // UTF-8 is mandated to be supported in Java, so this should never happen.
            throw new RuntimeException(e);
        }
    }

    return allParams.build().asMap();
}

From source file:com.facebook.presto.raptor.storage.TemporalCompactionSetCreator.java

private static Multimap<Long, ShardMetadata> getShardsByDays(Set<ShardMetadata> shardMetadata, Type type) {
    // bucket shards by the start day
    ImmutableMultimap.Builder<Long, ShardMetadata> shardsByDays = ImmutableMultimap.builder();

    // skip shards that do not have temporal information
    shardMetadata.stream().filter(shard -> shard.getRangeStart().isPresent() && shard.getRangeEnd().isPresent())
            .forEach(shard -> {/* ww  w.j  a  va 2s.  c o  m*/
                long day = determineDay(shard.getRangeStart().getAsLong(), shard.getRangeEnd().getAsLong(),
                        type);
                shardsByDays.put(day, shard);
            });
    return shardsByDays.build();
}

From source file:net.freifunk.autodeploy.firmware.FirmwareServiceImpl.java

@Override
public Multimap<Device, Firmware> getAvailableDeviceFirmwareMappings(final File firmwareImageDirectory) {
    Preconditions.checkState(firmwareImageDirectory.exists(), "Directory not found: " + firmwareImageDirectory);
    Preconditions.checkState(firmwareImageDirectory.isDirectory(),
            "Not a directory: " + firmwareImageDirectory);

    final Builder<Device, Firmware> builder = ImmutableMultimap.builder();

    for (final Firmware firmware : getSupportedFirmwares()) {
        for (final Device device : _deviceService.getSupportedDevices()) {
            final File image = toFirmwareImageFile(firmwareImageDirectory, firmware, device);
            if (image.exists() && image.isFile()) {
                builder.put(device, firmware);
            }/*from   ww w . j  a va 2 s. c  o m*/
        }
    }

    return builder.build();
}

From source file:org.apache.twill.internal.json.ArgumentsCodec.java

@Override
public Arguments deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {
    JsonObject jsonObj = json.getAsJsonObject();
    List<String> arguments = context.deserialize(jsonObj.get("arguments"), new TypeToken<List<String>>() {
    }.getType());/*w w  w .  j  av  a  2  s.  co  m*/
    Map<String, Collection<String>> args = context.deserialize(jsonObj.get("runnableArguments"),
            new TypeToken<Map<String, Collection<String>>>() {
            }.getType());

    ImmutableMultimap.Builder<String, String> builder = ImmutableMultimap.builder();
    for (Map.Entry<String, Collection<String>> entry : args.entrySet()) {
        builder.putAll(entry.getKey(), entry.getValue());
    }
    return new Arguments(arguments, builder.build());
}