Example usage for com.google.common.collect ImmutableMap.Builder put

List of usage examples for com.google.common.collect ImmutableMap.Builder put

Introduction

In this page you can find the example usage for com.google.common.collect ImmutableMap.Builder put.

Prototype

public final V put(K k, V v) 

Source Link

Usage

From source file:com.opengamma.strata.loader.csv.FxRatesCsvLoader.java

/**
 * Parses one or more CSV format FX rate files.
 * <p>//from  w ww. j  a va 2  s . c  om
 * A predicate is specified that is used to filter the dates that are returned.
 * This could match a single date, a set of dates or all dates.
 * <p>
 * If the files contain a duplicate entry an exception will be thrown.
 * 
 * @param datePredicate  the predicate used to select the dates
 * @param charSources  the CSV character sources
 * @return the loaded FX rates, mapped by {@link LocalDate} and {@linkplain FxRateId rate ID}
 * @throws IllegalArgumentException if the files contain a duplicate entry
 */
public static ImmutableMap<LocalDate, ImmutableMap<FxRateId, FxRate>> parse(Predicate<LocalDate> datePredicate,
        Collection<CharSource> charSources) {

    // builder ensures keys can only be seen once
    Map<LocalDate, ImmutableMap.Builder<FxRateId, FxRate>> mutableMap = new HashMap<>();
    for (CharSource charSource : charSources) {
        parseSingle(datePredicate, charSource, mutableMap);
    }
    ImmutableMap.Builder<LocalDate, ImmutableMap<FxRateId, FxRate>> builder = ImmutableMap.builder();
    for (Entry<LocalDate, Builder<FxRateId, FxRate>> entry : mutableMap.entrySet()) {
        builder.put(entry.getKey(), entry.getValue().build());
    }
    return builder.build();
}

From source file:no.ssb.vtl.script.expressions.FunctionExpression.java

@VisibleForTesting
static Map<String, VTLExpression> mergeArguments(VTLFunction.Signature signature, List<VTLExpression> arguments,
        Map<String, VTLExpression> namedArguments) {

    // Check unnamed arguments count.
    checkArgument(arguments.size() <= signature.size(), TOO_MANY_ARGUMENTS, signature.size(), arguments.size());

    ImmutableMap.Builder<String, VTLExpression> builder = ImmutableMap.builder();

    // Match the list with the signature names.
    Iterator<String> namesIterator = signature.keySet().iterator();
    for (VTLExpression argument : arguments) {
        builder.put(namesIterator.next(), argument);
    }/*from w ww.j a  va2s. co m*/

    // Check for duplicates
    Set<String> duplicates = Sets.intersection(namedArguments.keySet(), builder.build().keySet());
    checkArgument(duplicates.isEmpty(), DUPLICATE_ARGUMENTS, String.join(", ", duplicates));

    ImmutableMap<String, VTLExpression> computedArguments = builder.putAll(namedArguments).build();

    // Check for unknown arguments.
    Set<String> unknown = Sets.difference(computedArguments.keySet(), signature.keySet());
    checkArgument(unknown.isEmpty(), UNKNOWN_ARGUMENTS, String.join(", ", unknown));

    // Check for missing arguments
    Set<String> required = Maps.filterValues(signature, VTLFunction.Argument::isRequired).keySet();
    Set<String> missing = Sets.difference(required, computedArguments.keySet());
    checkArgument(missing.isEmpty(), MISSING_ARGUMENTS, String.join(", ", missing));

    return computedArguments;
}

From source file:com.google.template.soy.shared.internal.InternalPlugins.java

public static ImmutableMap<String, SoySourceFunction> fromFunctions(
        Iterable<? extends SoySourceFunction> functions) {
    ImmutableMap.Builder<String, SoySourceFunction> builder = ImmutableMap.builder();
    for (SoySourceFunction fn : functions) {
        SoyFunctionSignature sig = fn.getClass().getAnnotation(SoyFunctionSignature.class);
        checkState(sig != null, "Missing @SoyFunctionSignature on %s", fn.getClass());
        builder.put(sig.name(), fn);
    }/*  w w  w .  j ava 2  s .co m*/
    return builder.build();
}

From source file:com.fatboyindustrial.raygun.KeyMaster.java

/**
 * Parses the given string with the encoded hostname/API key pairings.
 * @param encoded The input string with values in {@code hostname[KEY]hostname[KEY]} format.
 * @return The mapping of hostname to API keys.
 * @throws IllegalArgumentException If the string is not in the required format.
 *///from  w w w  . ja  va2  s  .  c  o  m
@VisibleForTesting
protected static ImmutableMap<String, String> parseNamed(final String encoded) throws IllegalArgumentException {
    final ImmutableMap.Builder<String, String> map = ImmutableMap.builder();

    for (final String str : Splitter.on(' ').split(encoded)) {
        final int pivot = str.indexOf(':');
        if (pivot == -1) {
            throw new IllegalArgumentException("invalid format: " + str);
        }

        map.put(str.substring(0, pivot), str.substring(pivot + 1));
    }

    return map.build();
}

From source file:com.facebook.buck.io.file.PathListing.java

/**
 * Lists paths in descending modified time order, excluding any paths which bring the number of
 * files over {@code maxNumPaths} or over {@code totalSizeFilter} bytes in size.
 *///from ww  w  . j a v  a  2 s.c o  m
public static ImmutableSortedSet<Path> listMatchingPathsWithFilters(Path pathToGlob, String globPattern,
        PathModifiedTimeFetcher pathModifiedTimeFetcher, FilterMode filterMode, OptionalInt maxPathsFilter,
        Optional<Long> totalSizeFilter) throws IOException {

    // Fetch the modification time of each path and build a map of
    // (path => modification time) pairs.
    ImmutableMap.Builder<Path, FileTime> pathFileTimesBuilder = ImmutableMap.builder();
    try (DirectoryStream<Path> stream = Files.newDirectoryStream(pathToGlob, globPattern)) {
        for (Path path : stream) {
            try {
                pathFileTimesBuilder.put(path, pathModifiedTimeFetcher.getLastModifiedTime(path));
            } catch (NoSuchFileException e) {
                // Ignore the path.
                continue;
            }
        }
    }
    ImmutableMap<Path, FileTime> pathFileTimes = pathFileTimesBuilder.build();

    ImmutableSortedSet<Path> paths = ImmutableSortedSet.copyOf(Ordering.natural()
            // Order the keys of the map (the paths) by their values (the file modification
            // times).
            .onResultOf(Functions.forMap(pathFileTimes))
            // If two keys of the map have the same value, fall back to key order.
            .compound(Ordering.natural())
            // Use descending order.
            .reverse(), pathFileTimes.keySet());

    paths = applyNumPathsFilter(paths, filterMode, maxPathsFilter);
    paths = applyTotalSizeFilter(paths, filterMode, totalSizeFilter);
    return paths;
}

From source file:org.apache.cassandra.hints.HintsService.java

private static ImmutableMap<String, Object> createDescriptorParams() {
    ImmutableMap.Builder<String, Object> builder = ImmutableMap.builder();

    ParameterizedClass compressionConfig = DatabaseDescriptor.getHintsCompression();
    if (compressionConfig != null) {
        ImmutableMap.Builder<String, Object> compressorParams = ImmutableMap.builder();

        compressorParams.put(ParameterizedClass.CLASS_NAME, compressionConfig.class_name);
        if (compressionConfig.parameters != null) {
            compressorParams.put(ParameterizedClass.PARAMETERS, compressionConfig.parameters);
        }/*from  w ww . ja  v a2  s.c o m*/
        builder.put(HintsDescriptor.COMPRESSION, compressorParams.build());
    }

    return builder.build();
}

From source file:com.opengamma.collect.io.IniFile.java

/**
 * Parses the specified source as an INI file.
 * <p>/*ww  w .  j  a v a  2 s .  c  om*/
 * This parses the specified character source expecting an INI file format.
 * The resulting instance can be queried for each section in the file.
 * 
 * @param source  the INI file resource
 * @return the INI file
 * @throws UncheckedIOException if an IO error occurs
 * @throws IllegalArgumentException if the configuration is invalid
 */
public static IniFile of(CharSource source) {
    ArgChecker.notNull(source, "source");
    try {
        Map<String, Multimap<String, String>> parsedIni = parse(source);
        ImmutableMap.Builder<String, PropertySet> builder = ImmutableMap.builder();
        parsedIni.forEach((sectionName, sectionData) -> builder.put(sectionName, PropertySet.of(sectionData)));
        return new IniFile(builder.build());
    } catch (IOException ex) {
        throw new UncheckedIOException(ex);
    }
}

From source file:com.github.caofangkun.bazelipse.command.IdeBuildInfo.java

/**
 * Constructs a map of label -> {@link IdeBuildInfo} from a list of files, parsing each files into
 * a {@link JSONObject} and then converting that {@link JSONObject} to an {@link IdeBuildInfo}
 * object./*from w w  w  .  jav a2  s.co m*/
 */
static ImmutableMap<String, IdeBuildInfo> getInfo(List<String> files) throws IOException, InterruptedException {
    ImmutableMap.Builder<String, IdeBuildInfo> infos = ImmutableMap.builder();
    for (String s : files) {
        if (!s.isEmpty()) {
            IdeBuildInfo buildInfo = new IdeBuildInfo(new JSONObject(new JSONTokener(new FileInputStream(s))));
            infos.put(buildInfo.label, buildInfo);
        }
    }
    return infos.build();
}

From source file:com.opengamma.strata.loader.csv.QuotesCsvLoader.java

/**
 * Parses one or more CSV format quote files.
 * <p>//from   w w w.j a va2  s. c  o m
 * A predicate is specified that is used to filter the dates that are returned.
 * This could match a single date, a set of dates or all dates.
 * <p>
 * If the files contain a duplicate entry an exception will be thrown.
 * 
 * @param datePredicate  the predicate used to select the dates
 * @param charSources  the CSV character sources
 * @return the loaded quotes, mapped by {@link LocalDate} and {@linkplain QuoteId quote ID}
 * @throws IllegalArgumentException if the files contain a duplicate entry
 */
public static ImmutableMap<LocalDate, ImmutableMap<QuoteId, Double>> parse(Predicate<LocalDate> datePredicate,
        Collection<CharSource> charSources) {

    // builder ensures keys can only be seen once
    Map<LocalDate, ImmutableMap.Builder<QuoteId, Double>> mutableMap = new HashMap<>();
    for (CharSource charSource : charSources) {
        parseSingle(datePredicate, charSource, mutableMap);
    }
    ImmutableMap.Builder<LocalDate, ImmutableMap<QuoteId, Double>> builder = ImmutableMap.builder();
    for (Entry<LocalDate, Builder<QuoteId, Double>> entry : mutableMap.entrySet()) {
        builder.put(entry.getKey(), entry.getValue().build());
    }
    return builder.build();
}

From source file:com.mingo.parser.xml.dom.DomUtil.java

/**
 * Transform node attributes to map.// w  ww  . j a va  2 s. c  om
 *
 * @param node {@link Node}
 * @return map : key - attribute name; value - attribute value
 */
public static Map<String, String> getAttributes(Node node) {
    Map<String, String> attributes = ImmutableMap.of();
    if (node.hasAttributes()) {
        ImmutableMap.Builder builder = ImmutableMap.builder();
        // get attributes names and values
        NamedNodeMap nodeMap = node.getAttributes();
        for (int i = 0; i < nodeMap.getLength(); i++) {
            Node currentNode = nodeMap.item(i);
            builder.put(currentNode.getNodeName(), currentNode.getNodeValue());
        }
        attributes = builder.build();
    }
    return attributes;
}