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:com.google.devtools.build.android.xml.PublicXmlResourceValue.java

@Override
public int serializeTo(int sourceId, Namespaces namespaces, OutputStream output) throws IOException {
    Map<String, String> assignments = Maps.newLinkedHashMapWithExpectedSize(typeToId.size());
    for (Entry<ResourceType, Optional<Integer>> entry : typeToId.entrySet()) {
        Optional<Integer> value = entry.getValue();
        String stringValue = value.isPresent() ? value.get().toString() : MISSING_ID_VALUE;
        assignments.put(entry.getKey().toString(), stringValue);
    }/*from   w w  w . j a  va 2s  .  co m*/
    SerializeFormat.DataValue.Builder builder = XmlResourceValues.newSerializableDataValueBuilder(sourceId);
    builder.setXmlValue(builder.getXmlValueBuilder().setType(SerializeFormat.DataValueXml.XmlType.PUBLIC)
            .putAllNamespace(namespaces.asMap()).putAllMappedStringValue(assignments));
    return XmlResourceValues.serializeProtoDataValue(output, builder);
}

From source file:com.google.devtools.build.android.AndroidDataSerializer.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,//from  w ww  .  j a va 2 s . c om
                    FullyQualifiedName.isOverwritable(resourceName) ? consumers.overwritingConsumer
                            : consumers.combiningConsumer);
        } else {
            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());
        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:org.attribyte.wp.model.ShortcodeParser.java

/**
 * Parse attributes in a shortcode.//from ww w  .j av  a 2 s . c  o m
 * @param attrString The attribute string.
 * @return The map of attributes. Keys are <em>lower-case</em>.
 * @throws ParseException on invalid shortcode.
 */
private static Map<String, String> parseAttributes(String attrString) throws ParseException {

    AttributeString str = new AttributeString(attrString);
    Map<String, String> attributes = Maps.newLinkedHashMapWithExpectedSize(4); //Preserve order...
    AttrState state = AttrState.NAME;
    String currName = "";
    String currString = "";
    int currPos = 0;
    while ((currString = str.nextString()) != null) {
        switch (state) {
        case NAME:
            if (str.ch == '=') {
                currName = currString;
                state = AttrState.VALUE;
            } else {
                attributes.put(String.format("$%d", currPos++), currString);
            }
            break;
        case VALUE:
            attributes.put(currName.toLowerCase(), currString);
            state = AttrState.NAME;
            break;
        }
    }
    return attributes;
}

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

/**
 * Fetch the skylark loads for this BUILD file. If any of them haven't been computed yet,
 * returns null.//from   ww  w . jav  a2s  . c  o m
 */
@Nullable
static SkylarkImportResult fetchImportsFromBuildFile(Path buildFilePath, PackageIdentifier packageId,
        BuildFileAST buildFileAST, Environment env,
        SkylarkImportLookupFunction skylarkImportLookupFunctionForInlining)
        throws PackageFunctionException, InterruptedException {
    Preconditions.checkArgument(!packageId.getRepository().isDefault());

    ImmutableList<SkylarkImport> imports = buildFileAST.getImports();
    Map<String, Extension> importMap = Maps.newHashMapWithExpectedSize(imports.size());
    ImmutableList.Builder<SkylarkFileDependency> fileDependencies = ImmutableList.builder();
    ImmutableMap<String, Label> importPathMap;

    // Find the labels corresponding to the load statements.
    Label labelForCurrBuildFile;
    try {
        labelForCurrBuildFile = Label.create(packageId, "BUILD");
    } catch (LabelSyntaxException e) {
        // Shouldn't happen; the Label is well-formed by construction.
        throw new IllegalStateException(e);
    }
    try {
        importPathMap = SkylarkImportLookupFunction.findLabelsForLoadStatements(imports, labelForCurrBuildFile,
                env);
        if (importPathMap == null) {
            return null;
        }
    } catch (SkylarkImportFailedException e) {
        throw new PackageFunctionException(new BuildFileContainsErrorsException(packageId, e.getMessage()),
                Transience.PERSISTENT);
    }

    // Look up and load the imports.
    ImmutableCollection<Label> importLabels = importPathMap.values();
    List<SkyKey> importLookupKeys = Lists.newArrayListWithExpectedSize(importLabels.size());
    boolean inWorkspace = buildFilePath.getBaseName().endsWith("WORKSPACE");
    for (Label importLabel : importLabels) {
        importLookupKeys.add(SkylarkImportLookupValue.key(importLabel, inWorkspace));
    }
    Map<SkyKey, SkyValue> skylarkImportMap = Maps.newHashMapWithExpectedSize(importPathMap.size());
    boolean valuesMissing = false;

    try {
        if (skylarkImportLookupFunctionForInlining == null) {
            // Not inlining
            Map<SkyKey, ValueOrException2<SkylarkImportFailedException, InconsistentFilesystemException>> skylarkLookupResults = env
                    .getValuesOrThrow(importLookupKeys, SkylarkImportFailedException.class,
                            InconsistentFilesystemException.class);
            valuesMissing = env.valuesMissing();
            for (Map.Entry<SkyKey, ValueOrException2<SkylarkImportFailedException, InconsistentFilesystemException>> entry : skylarkLookupResults
                    .entrySet()) {
                // Fetching the value will raise any deferred exceptions
                skylarkImportMap.put(entry.getKey(), entry.getValue().get());
            }
        } else {
            // Inlining calls to SkylarkImportLookupFunction
            LinkedHashMap<Label, SkylarkImportLookupValue> alreadyVisitedImports = Maps
                    .newLinkedHashMapWithExpectedSize(importLookupKeys.size());
            for (SkyKey importLookupKey : importLookupKeys) {
                SkyValue skyValue = skylarkImportLookupFunctionForInlining
                        .computeWithInlineCalls(importLookupKey, env, alreadyVisitedImports);
                if (skyValue == null) {
                    Preconditions.checkState(env.valuesMissing(), "no skylark import value for %s",
                            importLookupKey);
                    // We continue making inline calls even if some requested values are missing, to
                    // maximize the number of dependent (non-inlined) SkyFunctions that are requested, thus
                    // avoiding a quadratic number of restarts.
                    valuesMissing = true;
                } else {
                    skylarkImportMap.put(importLookupKey, skyValue);
                }
            }

        }
    } catch (SkylarkImportFailedException e) {
        throw new PackageFunctionException(new BuildFileContainsErrorsException(packageId, e.getMessage()),
                Transience.PERSISTENT);
    } catch (InconsistentFilesystemException e) {
        throw new PackageFunctionException(new NoSuchPackageException(packageId, e.getMessage(), e),
                Transience.PERSISTENT);
    }

    if (valuesMissing) {
        // Some imports are unavailable.
        return null;
    }

    // Process the loaded imports.
    for (Entry<String, Label> importEntry : importPathMap.entrySet()) {
        String importString = importEntry.getKey();
        Label importLabel = importEntry.getValue();
        SkyKey keyForLabel = SkylarkImportLookupValue.key(importLabel, inWorkspace);
        SkylarkImportLookupValue importLookupValue = (SkylarkImportLookupValue) skylarkImportMap
                .get(keyForLabel);
        importMap.put(importString, importLookupValue.getEnvironmentExtension());
        fileDependencies.add(importLookupValue.getDependency());
    }

    return new SkylarkImportResult(importMap, transitiveClosureOfLabels(fileDependencies.build()));
}