Example usage for com.google.common.collect Maps newLinkedHashMapWithExpectedSize

List of usage examples for com.google.common.collect Maps newLinkedHashMapWithExpectedSize

Introduction

In this page you can find the example usage for com.google.common.collect Maps newLinkedHashMapWithExpectedSize.

Prototype

public static <K, V> LinkedHashMap<K, V> newLinkedHashMapWithExpectedSize(int expectedSize) 

Source Link

Document

Creates a LinkedHashMap instance, with a high enough "initial capacity" that it should hold expectedSize elements without growth.

Usage

From source file:cn.edu.zjnu.acm.judge.util.URIBuilder.java

private URIBuilder(String path, Map<String, String[]> query) {
    this.path = path;
    this.query = Maps.newLinkedHashMapWithExpectedSize(query.size());
    query.forEach(this::replaceQueryParam);
}

From source file:org.ambraproject.rhino.content.xml.ManifestXml.java

private static <T, K> ImmutableMap<K, T> mapByUniqueKeys(Collection<? extends T> values,
        Function<T, K> keyFunction, Function<K, String> parentDescription) {
    Map<K, T> map = Maps.newLinkedHashMapWithExpectedSize(values.size());
    for (T value : values) {
        K key = Objects.requireNonNull(keyFunction.apply(Objects.requireNonNull(value)));
        T previous = map.put(key, value);
        if (previous != null) {
            throw new ManifestDataException(parentDescription.apply(key));
        }/*from www.  j  a  v  a2s.co  m*/
    }
    return ImmutableMap.copyOf(map);
}

From source file:org.eclipse.che.workspace.infrastructure.docker.environment.convert.ComposeEnvironmentConverter.java

@Override
public DockerEnvironment convert(InternalEnvironment environment) throws ValidationException {
    if (!(environment instanceof ComposeEnvironment)) {
        throw new ValidationException("The specified environment is not compose environment");
    }//  ww  w .jav  a  2 s.  c  om
    ComposeEnvironment composeEnv = (ComposeEnvironment) environment;

    LinkedHashMap<String, DockerContainerConfig> containers = Maps
            .newLinkedHashMapWithExpectedSize(composeEnv.getServices().size());
    for (Map.Entry<String, ComposeService> composeServiceEntry : composeEnv.getServices().entrySet()) {
        ComposeService service = composeServiceEntry.getValue();

        DockerContainerConfig cheContainer = new DockerContainerConfig().setCommand(service.getCommand())
                .setContainerName(service.getContainerName()).setDependsOn(service.getDependsOn())
                .setEntrypoint(service.getEntrypoint()).setEnvironment(service.getEnvironment())
                .setExpose(service.getExpose()).setImage(service.getImage()).setLabels(service.getLabels())
                .setLinks(service.getLinks()).setMemLimit(service.getMemLimit())
                .setNetworks(service.getNetworks()).setPorts(service.getPorts())
                .setVolumes(service.getVolumes()).setVolumesFrom(service.getVolumesFrom());

        if (service.getBuild() != null) {
            cheContainer.setBuild(new DockerBuildContext().setContext(service.getBuild().getContext())
                    .setDockerfilePath(service.getBuild().getDockerfile())
                    .setArgs(service.getBuild().getArgs()));
        }

        containers.put(composeServiceEntry.getKey(), cheContainer);
    }
    return new DockerEnvironment(environment.getRecipe(), environment.getMachines(), environment.getWarnings())
            .setContainers(containers);
}

From source file:io.bazel.rules.closure.webfiles.Webset.java

/**
 * Loads graph of web files from proto manifests.
 *
 * @param manifests set of web rule target proto files in reverse topological order
 * @return set of web files and relationships between them, which could be mutated, although
 *     adding a single key will most likely result in a full rehash
 *///from  w w w . ja  v  a2  s.  c  o m
public static Webset load(Map<Path, WebfileManifestInfo> manifests, WebpathInterner interner) {
    int webfileCapacity = 0;
    int unlinkCapacity = 16; // LinkedHashMultimap#DEFAULT_KEY_CAPACITY
    for (WebfileManifestInfo manifest : manifests.values()) {
        webfileCapacity += manifest.getWebfileCount();
        unlinkCapacity = Math.max(unlinkCapacity, manifest.getUnlinkCount());
    }
    Map<Webpath, Webfile> webfiles = Maps.newLinkedHashMapWithExpectedSize(webfileCapacity);
    Multimap<Webpath, Webpath> links = LinkedHashMultimap.create(webfileCapacity, 4);
    Multimap<Webpath, Webpath> unlinks = LinkedHashMultimap.create(unlinkCapacity, 4);
    for (Map.Entry<Path, WebfileManifestInfo> entry : manifests.entrySet()) {
        Path manifestPath = entry.getKey();
        Path zipPath = WebfilesUtils.getIncrementalZipPath(manifestPath);
        WebfileManifestInfo manifest = entry.getValue();
        String label = manifest.getLabel();
        for (WebfileInfo info : manifest.getWebfileList()) {
            Webpath webpath = interner.get(info.getWebpath());
            webfiles.put(webpath, Webfile.create(webpath, zipPath, label, info));
        }
        for (MultimapInfo mapping : manifest.getLinkList()) {
            Webpath from = interner.get(mapping.getKey());
            for (Webpath to : Iterables.transform(mapping.getValueList(), interner)) {
                // When compiling web_library rules, if the strict dependency checking invariant holds
                // true, we can choose to only load adjacent manifests, rather than transitive ones. The
                // adjacent manifests may contain links to transitive web files which will not be in the
                // webfiles map.
                if (webfiles.containsKey(to)) {
                    links.put(from, to);
                    checkArgument(!unlinks.containsEntry(from, to),
                            "Has a use case for resurrected links been discovered? %s -> %s", from, to);
                }
            }
        }
        for (MultimapInfo mapping : manifest.getUnlinkList()) {
            unlinks.putAll(interner.get(mapping.getKey()),
                    Collections2.transform(mapping.getValueList(), interner));
        }
    }
    for (Map.Entry<Webpath, Webpath> entry : unlinks.entries()) {
        links.remove(entry.getKey(), entry.getValue());
    }
    unlinks.clear();
    return new AutoValue_Webset(webfiles, links, interner);
}

From source file:com.google.gerrit.metrics.Description.java

/**
 * Describe a metric.//w  ww.  j  a va2 s .  c  o m
 *
 * @param helpText a short one-sentence string explaining the values captured by the metric. This
 *     may be made available to administrators as documentation in the reporting tools.
 */
public Description(String helpText) {
    annotations = Maps.newLinkedHashMapWithExpectedSize(4);
    annotations.put(DESCRIPTION, helpText);
}

From source file:com.facebook.buck.core.select.impl.SelectorFactory.java

/**
 * Creates a {@link Selector} by converting a given map.
 *
 * @param rawAttributes a map with attributes represented in a format produced by build file
 *     parsers (i.e. non-coerced.)/*from w ww .ja va  2  s  .c  om*/
 * @param elementTypeCoercer coercer that is used to coerce values of the given map
 */
public <T> Selector<T> createSelector(CellPathResolver cellPathResolver, ProjectFilesystem filesystem,
        Path pathRelativeToProjectRoot, Map<String, ?> rawAttributes, TypeCoercer<T> elementTypeCoercer,
        String noMatchMessage) throws CoerceFailedException {
    LinkedHashMap<SelectorKey, T> result = Maps.newLinkedHashMapWithExpectedSize(rawAttributes.size());
    Set<SelectorKey> nullConditions = new HashSet<>();
    boolean foundDefaultCondition = false;
    for (Entry<String, ?> entry : rawAttributes.entrySet()) {
        String key = entry.getKey();
        SelectorKey selectorKey;
        if (key.equals(SelectorKey.DEFAULT_KEYWORD)) {
            foundDefaultCondition = true;
            selectorKey = SelectorKey.DEFAULT;
        } else {
            selectorKey = new SelectorKey(buildTargetTypeCoercer.coerce(cellPathResolver, filesystem,
                    pathRelativeToProjectRoot, EmptyTargetConfiguration.INSTANCE, key));
        }
        if (entry.getValue() == Runtime.NONE) {
            result.remove(selectorKey);
            nullConditions.add(selectorKey);
        } else {
            result.put(selectorKey, elementTypeCoercer.coerce(cellPathResolver, filesystem,
                    pathRelativeToProjectRoot, EmptyTargetConfiguration.INSTANCE, entry.getValue()));
            nullConditions.remove(selectorKey);
        }
    }

    return new Selector<>(ImmutableMap.copyOf(result), ImmutableSet.copyOf(nullConditions), noMatchMessage,
            foundDefaultCondition);
}

From source file:com.google.javascript.jscomp.NameBasedDefinitionProvider.java

public NameBasedDefinitionProvider(AbstractCompiler compiler, boolean allowComplexFunctionDefs) {
    this.compiler = compiler;
    this.allowComplexFunctionDefs = allowComplexFunctionDefs;
    int numInputs = compiler.getNumberOfInputs();
    // Estimates below were generated by experimentation with large Google projects.
    this.definitionsByName = LinkedHashMultimap.create(numInputs * 15, 1);
    int estimatedDefinitionSites = numInputs * 22;
    this.definitionSitesByDefinitionSiteNode = Maps.newLinkedHashMapWithExpectedSize(estimatedDefinitionSites);
    this.definitionSitesByScopeNode = HashMultimap.create(estimatedDefinitionSites, 1);
    this.definitionNodes = Sets.newHashSetWithExpectedSize(estimatedDefinitionSites);
}

From source file:org.apache.bookkeeper.server.http.service.ListBookieInfoService.java

@Override
public HttpServiceResponse handle(HttpServiceRequest request) throws Exception {
    HttpServiceResponse response = new HttpServiceResponse();

    if (HttpServer.Method.GET == request.getMethod()) {
        ClientConfiguration clientConf = new ClientConfiguration(conf);
        clientConf.setDiskWeightBasedPlacementEnabled(true);
        BookKeeper bk = new BookKeeper(clientConf);

        Map<BookieSocketAddress, BookieInfoReader.BookieInfo> map = bk.getBookieInfo();
        if (map.size() == 0) {
            bk.close();/*from  w w  w . j  a v  a 2  s .c  o  m*/
            response.setCode(HttpServer.StatusCode.NOT_FOUND);
            response.setBody("Not found any Bookie info.");
            return response;
        }

        /**
         * output:
         *  {
         *    "bookieAddress" : {free: xxx, total: xxx}",
         *    "bookieAddress" : {free: xxx, total: xxx},
         *    ...
         *    "clusterInfo" : {total_free: xxx, total: xxx}"
         *  }
         */
        LinkedHashMap<String, String> output = Maps.newLinkedHashMapWithExpectedSize(map.size());
        Long totalFree = 0L, total = 0L;
        for (Map.Entry<BookieSocketAddress, BookieInfoReader.BookieInfo> infoEntry : map.entrySet()) {
            BookieInfoReader.BookieInfo bInfo = infoEntry.getValue();
            output.put(infoEntry.getKey().toString(),
                    ": {Free: " + bInfo.getFreeDiskSpace() + getReadable(bInfo.getFreeDiskSpace()) + ", Total: "
                            + bInfo.getTotalDiskSpace() + getReadable(bInfo.getTotalDiskSpace()) + "},");
            totalFree += bInfo.getFreeDiskSpace();
            total += bInfo.getTotalDiskSpace();
        }
        output.put("ClusterInfo: ", "{Free: " + totalFree + getReadable(totalFree) + ", Total: " + total
                + getReadable(total) + "}");

        bk.close();

        String jsonResponse = JsonUtil.toJson(output);
        LOG.debug("output body:" + jsonResponse);
        response.setBody(jsonResponse);
        response.setCode(HttpServer.StatusCode.OK);
        return response;
    } else {
        response.setCode(HttpServer.StatusCode.NOT_FOUND);
        response.setBody("Not found method. Should be GET method");
        return response;
    }
}

From source file:com.google.devtools.build.android.AndroidDataDeserializer.java

private void readEntriesSegment(KeyValueConsumers consumers, InputStream in, FileSystem currentFileSystem,
        Header header) throws IOException {
    int numberOfEntries = header.getEntryCount();
    Map<DataKey, KeyValueConsumer<DataKey, ? extends DataValue>> keys = Maps
            .newLinkedHashMapWithExpectedSize(numberOfEntries);
    for (int i = 0; i < numberOfEntries; i++) {
        SerializeFormat.DataKey protoKey = SerializeFormat.DataKey.parseDelimitedFrom(in);
        if (protoKey.hasResourceType()) {
            FullyQualifiedName resourceName = FullyQualifiedName.fromProto(protoKey);
            keys.put(resourceName, resourceName.isOverwritable() ? consumers.overwritingConsumer
                    : consumers.combiningConsumer);
        } else {/* w  ww.  j  a  v  a  2  s.  co  m*/
            keys.put(RelativeAssetPath.fromProto(protoKey, currentFileSystem), consumers.assetConsumer);
        }
    }

    // Read back the sources table.
    DataSourceTable sourceTable = DataSourceTable.read(in, currentFileSystem, header);

    // TODO(corysmith): Make this a lazy read of the values.
    for (Entry<DataKey, KeyValueConsumer<DataKey, ?>> entry : keys.entrySet()) {
        SerializeFormat.DataValue protoValue = SerializeFormat.DataValue.parseDelimitedFrom(in);
        DataSource source = sourceTable.sourceFromId(protoValue.getSourceId());
        int nameCount = source.getPath().getNameCount();
        String shortPath = source.getPath().subpath(nameCount - 2, nameCount).toString();
        if (filteredResources.contains(shortPath)) {
            // Skip files that were filtered out during analysis.
            // TODO(asteinb): Properly filter out these files from android_library symbol files during
            // analysis instead, and remove this list.
            continue;
        }
        if (protoValue.hasXmlValue()) {
            // TODO(corysmith): Figure out why the generics are wrong.
            // If I use Map<DataKey, KeyValueConsumer<DataKey, ? extends DataValue>>, I can put
            // consumers into the map, but I can't call consume.
            // If I use Map<DataKey, KeyValueConsumer<DataKey, ? super DataValue>>, I can consume
            // but I can't put.
            // Same for below.
            @SuppressWarnings("unchecked")
            KeyValueConsumer<DataKey, DataValue> value = (KeyValueConsumer<DataKey, DataValue>) entry
                    .getValue();
            value.consume(entry.getKey(), DataResourceXml.from(protoValue, source));
        } else {
            @SuppressWarnings("unchecked")
            KeyValueConsumer<DataKey, DataValue> value = (KeyValueConsumer<DataKey, DataValue>) entry
                    .getValue();
            value.consume(entry.getKey(), DataValueFile.of(source));
        }
    }
}

From source file:com.google.devtools.build.android.AndroidParsedDataDeserializer.java

private void readEntriesSegment(KeyValueConsumers consumers, InputStream in, FileSystem currentFileSystem,
        Header header) throws IOException {
    int numberOfEntries = header.getEntryCount();
    Map<DataKey, KeyValueConsumer<DataKey, ? extends DataValue>> keys = Maps
            .newLinkedHashMapWithExpectedSize(numberOfEntries);
    for (int i = 0; i < numberOfEntries; i++) {
        SerializeFormat.DataKey protoKey = SerializeFormat.DataKey.parseDelimitedFrom(in);
        if (protoKey.hasResourceType()) {
            FullyQualifiedName resourceName = FullyQualifiedName.fromProto(protoKey);
            keys.put(resourceName, resourceName.isOverwritable() ? consumers.overwritingConsumer
                    : consumers.combiningConsumer);
        } else {/*w  w w .j a  va2 s .c  om*/
            keys.put(RelativeAssetPath.fromProto(protoKey, currentFileSystem), consumers.assetConsumer);
        }
    }

    // Read back the sources table.
    DataSourceTable sourceTable = DataSourceTable.read(in, currentFileSystem, header);

    // TODO(corysmith): Make this a lazy read of the values.
    for (Map.Entry<DataKey, KeyValueConsumer<DataKey, ?>> entry : keys.entrySet()) {
        SerializeFormat.DataValue protoValue = SerializeFormat.DataValue.parseDelimitedFrom(in);
        DataSource source = sourceTable.sourceFromId(protoValue.getSourceId());
        // Compose the `shortPath` manually to ensure it uses a forward slash.
        // Using Path.subpath would return a backslash-using path on Windows.
        String shortPath = source.getPath().getParent().getFileName() + "/" + source.getPath().getFileName();
        if (filteredResources.contains(shortPath) && !Files.exists(source.getPath())) {
            // Skip files that were filtered out during analysis.
            // TODO(asteinb): Properly filter out these files from android_library symbol files during
            // analysis instead, and remove this list.
            continue;
        }
        if (protoValue.hasXmlValue()) {
            // TODO(corysmith): Figure out why the generics are wrong.
            // If I use Map<DataKey, KeyValueConsumer<DataKey, ? extends DataValue>>, I can put
            // consumers into the map, but I can't call accept.
            // If I use Map<DataKey, KeyValueConsumer<DataKey, ? super DataValue>>, I can consume
            // but I can't put.
            // Same for below.
            @SuppressWarnings("unchecked")
            KeyValueConsumer<DataKey, DataValue> value = (KeyValueConsumer<DataKey, DataValue>) entry
                    .getValue();
            value.accept(entry.getKey(), DataResourceXml.from(protoValue, source));
        } else {
            @SuppressWarnings("unchecked")
            KeyValueConsumer<DataKey, DataValue> value = (KeyValueConsumer<DataKey, DataValue>) entry
                    .getValue();
            value.accept(entry.getKey(), DataValueFile.of(source));
        }
    }
}