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

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

Introduction

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

Prototype

public final void putAll(Map<? extends K, ? extends V> map) 

Source Link

Usage

From source file:org.prebake.service.bake.Oven.java

@Nonnull
Executor.Output<Boolean> executeActions(final Path workingDir, Product p,
        final ImmutableList.Builder<Path> paths, final Hash.Builder hashes) throws IOException {
    Executor execer = Executor.Factory.createJsExecutor();
    final WorkingFileChecker checker = new WorkingFileChecker(files.getVersionRoot(), workingDir);
    ExecFn execFn = new ExecFn(os, workingDir, checker, execService, logger);
    ImmutableMap.Builder<String, Object> actuals = ImmutableMap.builder();
    actuals.putAll(commonJsEnv);
    actuals.put("os", JsOperatingSystemEnv.makeJsInterface(workingDir, execFn));
    actuals.put("matching",
            // A function that finds inputs for actions.
            // We delay this instead of doing it in the action loop since
            // one action might produce files that are inputs to another.
            new SimpleMembranableFunction("", "matching", "paths", "globs") {
                MessageQueue mq = new MessageQueue();

                public ImmutableList<String> apply(Object[] argv) {
                    ImmutableList<Glob> inputGlobs = Glob.CONV.convert(argv[0], mq);
                    // Already vetted by Product parser.
                    if (mq.hasErrors()) {
                        throw new IllegalStateException();
                    }/*from w w w .  j a va 2s .c om*/
                    ImmutableGlobSet inputGlobSet = ImmutableGlobSet.of(inputGlobs);
                    List<Path> inputs;
                    try {
                        inputs = Lists.newArrayList(
                                WorkingDir.matching(workingDir, ImmutableSet.<Path>of(), inputGlobSet));
                    } catch (IOException ex) {
                        throw new RuntimeException(ex);
                    }
                    sortByGlobs(inputs, inputGlobSet);
                    ImmutableList.Builder<String> b = ImmutableList.builder();
                    for (Path p : inputs) {
                        b.add(p.toString());
                    }
                    return b.build();
                }
            });
    StringBuilder productJs = new StringBuilder();
    {
        Map<String, String> toolNameToLocalName = Maps.newHashMap();
        for (Action a : p.actions) {
            // First, load each tool module.
            String toolName = a.toolName;
            if (toolNameToLocalName.containsKey(toolName)) {
                continue;
            }
            String localName = "tool_" + toolNameToLocalName.size();
            toolNameToLocalName.put(toolName, localName);
            ToolContent tool = toolbox.getTool(toolName);
            if (tool.fh.getHash() != null) {
                paths.add(tool.fh.getPath());
                hashes.withHash(tool.fh.getHash());
            }
            ImmutableMap<String, ?> extraEnv = tool.isBuiltin ? BuiltinToolHooks.extraEnvironmentFor(toolName)
                    : ImmutableMap.<String, Object>of();
            actuals.put(localName,
                    Executor.Input.builder(tool.fh.getContentAsString(Charsets.UTF_8), tool.fh.getPath())
                            .withActuals(commonJsEnv).withActuals(extraEnv).build());
        }
        JsonSink productJsSink = new JsonSink(productJs);
        // Second, store the product.
        productJsSink.write("var product = ").writeValue(p).write(";\n");
        productJsSink.write("product.name = ").writeValue(p.name).write(";\n");
        productJsSink.write("product = Object.frozenCopy(product);\n");
        // If the product wants to control how actions are executed, then wrap
        // the tool execution in a call to the mobile function product.bake.
        boolean thunkify = p.bake != null;
        productJsSink.write("(");
        // If there is a product.bake method, then we do something like
        //   product.bake([
        //       function () { return /* invoke action 0 */ },
        //       function () { return /* invoke action 1 */ },
        //       ...]);
        // so the result of the process is the result of product.bake which gets
        // a list of thunks : one per action.
        //
        // Otherwise, we provide a default bake which runs and waits for each in
        // order like:
        //   ((/* invoke action 0 */).run().waitFor() === 0
        //    && (/* invoke.action 1 */).run().waitFor() === 0
        //    && ...);
        if (thunkify) {
            productJsSink.write("product.bake([");
        }
        if (!thunkify && p.actions.isEmpty()) {
            productJsSink.write("true");
        }
        // Third, for each action, invoke its tool's run method with the proper
        // arguments.
        for (int i = 0, n = p.actions.size(); i < n; ++i) {
            if (i != 0) {
                productJsSink.write(thunkify ? "," : ") && (");
            }
            if (thunkify) {
                productJsSink.write("function () { return ");
            }
            // Fill in the /* invoke action x */ bits above with a call to the
            // tool like:
            //   tool_x.fire(matching(['foo/*.c']), product, product.actions[0], os)
            // where product is a frozen YSON object.
            // Matching is defined above, and os is defined in JsOperatingSystemEnv.
            Action action = p.actions.get(i);
            productJsSink.write(toolNameToLocalName.get(action.toolName)).write(".fire(matching(");
            action.inputs.toJson(productJsSink);
            // .slice(0) works around problem where membraned arrays don't
            // behave as arrays w.r.t. concat and other builtins.
            productJsSink.write(").slice(0),\n    product,\n    product.actions[").write(String.valueOf(i))
                    .write("],\n    os)\n");
            productJsSink.write(thunkify ? "}" : ".run().waitFor() === 0");
        }
        if (thunkify) {
            productJsSink.write("])");
        }
        productJsSink.write(");");
    }
    Executor.Input src = Executor.Input.builder(productJs.toString(), "product-" + p.name)
            // TODO: use the product plan file as the base dir so that loads in the
            // product's bake function happen relative to the plan file.
            // This requires us to take the source path into account when deciding
            // whether a product has changed since last build.
            .withBase(workingDir).withActuals(actuals.build()).build();
    // Set up output directories.
    {
        Set<Path> outPaths = Sets.newHashSet();
        for (Action a : p.actions) {
            for (Glob glob : a.outputs) {
                Path outPath = glob.getPathContainingAllMatches(workingDir);
                // We use 0700 since we're only operating in the working dir.
                if (outPaths.add(outPath)) {
                    Baker.mkdirs(outPath, 0700);
                }
            }
        }
    }
    Executor.Output<Boolean> runResult;
    try {
        // Run the script.
        runResult = execer.run(Boolean.class, logger, new PrebakeScriptLoader(files, paths, hashes), src);
    } finally {
        // We can't allow processes to keep mucking with the working directory
        // after we kill it and possibly recreate it for a rebuild.
        // If something wants to spawn long-lasting processes such as a
        // java compilation service, they can spawn a child process and disown it.
        if (execFn.killOpenProcesses()) {
            runResult = new Executor.Output<Boolean>(false, false, null);
        }
    }
    return runResult;
}

From source file:com.publictransitanalytics.scoregenerator.distance.SplitMergeDistanceClient.java

@Override
public Map<PointLocation, WalkingCosts> getDistances(final PointLocation point,
        final Set<PointLocation> consideredPoints) throws DistanceClientException, InterruptedException {
    final List<PointLocation> consideredList = ImmutableList.copyOf(consideredPoints);
    int base = 0;
    final int total = consideredPoints.size();
    final ImmutableMap.Builder<PointLocation, WalkingCosts> resultBuilder = ImmutableMap.builder();
    while (base < total) {
        int end = Math.min(base + maxConsidered, total);
        final Set<PointLocation> consideredSubset = ImmutableSet.copyOf(consideredList.subList(base, end));
        final Map<PointLocation, WalkingCosts> distances = client.getDistances(point, consideredSubset);
        resultBuilder.putAll(distances);
        base = end;/*w  w w. j a  va  2 s  .  c  o m*/
    }
    return resultBuilder.build();
}

From source file:com.opengamma.strata.pricer.calibration.CurveCalibrator.java

private ImmutableMap<CurveName, JacobianCalibrationMatrix> updateJacobiansForGroup(
        ImmutableRatesProvider provider, ImmutableList<Trade> trades,
        ImmutableList<CurveParameterSize> orderGroup, ImmutableList<CurveParameterSize> orderPrev,
        ImmutableList<CurveParameterSize> orderAll,
        ImmutableMap<CurveName, JacobianCalibrationMatrix> jacobians) {

    // sensitivity to all parameters in the stated order
    int totalParamsAll = orderAll.stream().mapToInt(e -> e.getParameterCount()).sum();
    DoubleMatrix res = derivatives(trades, provider, orderAll, totalParamsAll);

    // jacobian direct
    int nbTrades = trades.size();
    int totalParamsGroup = orderGroup.stream().mapToInt(e -> e.getParameterCount()).sum();
    int totalParamsPrevious = totalParamsAll - totalParamsGroup;
    DoubleMatrix pDmCurrentMatrix = jacobianDirect(res, nbTrades, totalParamsGroup, totalParamsPrevious);

    // jacobian indirect: when totalParamsPrevious > 0
    DoubleMatrix pDmPrevious = jacobianIndirect(res, pDmCurrentMatrix, nbTrades, totalParamsGroup,
            totalParamsPrevious, orderPrev, jacobians);

    // add to the map of jacobians, one entry for each curve in this group
    ImmutableMap.Builder<CurveName, JacobianCalibrationMatrix> jacobianBuilder = ImmutableMap.builder();
    jacobianBuilder.putAll(jacobians);
    int startIndex = 0;
    for (CurveParameterSize order : orderGroup) {
        int paramCount = order.getParameterCount();
        double[][] pDmCurveArray = new double[paramCount][totalParamsAll];
        // copy data for previous groups
        if (totalParamsPrevious > 0) {
            for (int p = 0; p < paramCount; p++) {
                System.arraycopy(pDmPrevious.rowArray(startIndex + p), 0, pDmCurveArray[p], 0,
                        totalParamsPrevious);
            }//from   www.j a  v  a  2s. c  o  m
        }
        // copy data for this group
        for (int p = 0; p < paramCount; p++) {
            System.arraycopy(pDmCurrentMatrix.rowArray(startIndex + p), 0, pDmCurveArray[p],
                    totalParamsPrevious, totalParamsGroup);
        }
        // build final Jacobian matrix
        DoubleMatrix pDmCurveMatrix = DoubleMatrix.ofUnsafe(pDmCurveArray);
        jacobianBuilder.put(order.getName(), JacobianCalibrationMatrix.of(orderAll, pDmCurveMatrix));
        startIndex += paramCount;
    }
    return jacobianBuilder.build();
}

From source file:org.tendiwa.inflectible.inflection.LxWithSuppletivism.java

/**
 * Generates all word forms of this lexeme.
 * @return All word forms of this lexeme
 * @throws Exception If fails//from   ww  w.  j  a  v a 2  s  . c  om
 */
@SuppressWarnings("PMD.AvoidInstantiatingObjectsInLoops")
private ImmutableMap<GrammaticalMeaning, Spelling> forms() throws Exception {
    final ImmutableMap.Builder<GrammaticalMeaning, Spelling> builder = ImmutableMap.builder();
    final ImmutableSet<ImmutableSet<Grammeme>> headwordMeanings = this.headwords.keySet().stream()
            .map(Rethrowing.rethrowFunction(GrammaticalMeaning::grammemes))
            .collect(Collectors.toImmutableSet());
    builder.putAll(this.headwords);
    for (final GrammaticalMeaning meaning : this.part.meaningVariations()) {
        if (headwordMeanings.contains(meaning.grammemes())) {
            continue;
        }
        final GrammaticalMeaning closest = this.closestHeadwordMeaning(meaning);
        builder.put(meaning, this.part
                .lexeme(this.headwords.get(closest), new GmCombined(ImmutableList.of(this.persistent, closest)))
                .wordForm(meaning));
    }
    return builder.build();
}

From source file:com.viadeo.kasper.core.id.DefaultIDTransformer.java

private Map<ID, ID> doConvertAll(final Format targetFormat, Collection<ID> ids) {
    HashMultimap<ImmutablePair<String, Format>, ID> idsByVendorFormat = HashMultimap.create();
    for (ID id : ids) {
        idsByVendorFormat.put(ImmutablePair.of(id.getVendor(), id.getFormat()), id);
    }//from   w w w.  j a v a 2 s . c o  m

    ImmutableMap.Builder<ID, ID> convertedIds = ImmutableMap.builder();

    for (Map.Entry<ImmutablePair<String, Format>, Collection<ID>> entry : idsByVendorFormat.asMap()
            .entrySet()) {
        ImmutablePair<String, Format> key = entry.getKey();
        Collection<ID> values = entry.getValue();

        convertedIds.putAll(doConvert(key.first, key.second, targetFormat, values));
    }

    return convertedIds.build();
}

From source file:org.spongepowered.clean.SServer.java

@Override
public WorldProperties createWorldProperties(String folderName, WorldArchetype archetype) throws IOException {
    WorldProperties props = this.unloaded_worlds.get(folderName);
    if (props != null) {
        return props;
    }/*from  w ww  .ja  v  a  2  s  . c om*/
    props = new SWorldProperties(folderName, archetype);
    ImmutableMap.Builder<String, WorldProperties> builder = ImmutableMap.builder();
    builder.putAll(this.unloaded_worlds);
    builder.put(folderName, props);
    this.unloaded_worlds = builder.build();
    return props;
}

From source file:com.publictransitanalytics.scoregenerator.distance.RangedCachingReachabilityClient.java

@Override
public Map<PointLocation, WalkingCosts> getWalkingCosts(final PointLocation location,
        final LocalDateTime currentTime, final LocalDateTime cutoffTime)
        throws DistanceClientException, InterruptedException {

    final Duration duration = timeTracker.getDuration(currentTime, cutoffTime);

    final ImmutableMap.Builder<PointLocation, WalkingCosts> builder = ImmutableMap.builder();
    final Set<PointLocation> uncached;
    final boolean updateMaxStored;
    final Duration maxStored = store.getMaxStored(location);
    if (maxStored != null) {
        final Map<PointLocation, WalkingCosts> cached = store.get(location, duration);
        builder.putAll(cached);

        if (duration.compareTo(maxStored) > 0) {
            uncached = Sets.difference(points, cached.keySet());
            updateMaxStored = true;/* w w w  .j a va2s .c  o m*/
        } else {
            uncached = Collections.emptySet();
            updateMaxStored = false;
        }
    } else {
        uncached = points;
        updateMaxStored = true;
    }

    if (!uncached.isEmpty()) {
        final Map<PointLocation, WalkingCosts> estimatedCosts = estimationClient.getDistances(location,
                uncached);
        final Map<PointLocation, WalkingCosts> candidateEstimates = filterTimes(estimatedCosts, duration);
        final Set<PointLocation> candidates = candidateEstimates.keySet();

        if (!candidates.isEmpty()) {
            final Map<PointLocation, WalkingCosts> candidateCosts = distanceClient.getDistances(location,
                    candidates);
            final Map<PointLocation, WalkingCosts> filteredDistances = filterTimes(candidateCosts, duration);
            store.putAll(location, filteredDistances);
            builder.putAll(filteredDistances);
        }
    }

    if (updateMaxStored) {
        store.updateMaxStored(location, duration);
    }
    return builder.build();

}

From source file:com.google.api.codegen.packagegen.java.JavaGrpcPackageGenerator.java

@Override
public Map<String, GeneratedResult<Doc>> generate() {
    ImmutableMap.Builder<String, GeneratedResult<Doc>> results = new ImmutableMap.Builder<>();

    ProtoApiModel apiModel = new ProtoApiModel(model);
    ArrayList<PackageMetadataView> metadataViews = new ArrayList<>();
    metadataViews.addAll(transformer.transform(apiModel, config));

    for (PackageMetadataView view : metadataViews) {
        CommonSnippetSetRunner runner = new CommonSnippetSetRunner(view, false);
        results.putAll(runner.generate(view));
    }//from  w  w  w  .ja  va2  s . co  m
    return results.build();
}

From source file:org.apache.calcite.model.ModelHandler.java

/** Adds extra entries to an operand to a custom schema. */
protected Map<String, Object> operandMap(JsonSchema jsonSchema, Map<String, Object> operand) {
    if (operand == null) {
        return ImmutableMap.of();
    }/*from  w w  w. j  a v  a 2s  .  c  o m*/
    final ImmutableMap.Builder<String, Object> builder = ImmutableMap.builder();
    builder.putAll(operand);
    for (ExtraOperand extraOperand : ExtraOperand.values()) {
        if (!operand.containsKey(extraOperand.camelName)) {
            switch (extraOperand) {
            case MODEL_URI:
                builder.put(extraOperand.camelName, modelUri);
                break;
            case BASE_DIRECTORY:
                File f = null;
                if (!modelUri.startsWith("inline:")) {
                    final File file = new File(modelUri);
                    f = file.getParentFile();
                }
                if (f == null) {
                    f = new File("");
                }
                builder.put(extraOperand.camelName, f);
                break;
            case TABLES:
                if (jsonSchema instanceof JsonCustomSchema) {
                    builder.put(extraOperand.camelName, ((JsonCustomSchema) jsonSchema).tables);
                }
                break;
            }
        }
    }
    return builder.build();
}

From source file:io.prometheus.client.Registry.java

/**
 * <p>//from w  ww .  j  a v  a  2  s.  c  o m
 * Register a {@link Metric} with this {@link Registry}.
 * </p>
 * 
 * <p>
 * Whether or not a registration occurs depends on the following:
 * </p>
 * 
 * <ul>
 * <li>The metric's name is not empty.</li>
 * <li>The metric's name and label set have not already been registered.</li>
 * <li>The docstring is not empty.</li>
 * </ul>
 * 
 * <p>
 * Current limitations include the following:
 * </p>
 * <ul>
 * <li>Ensuring that double-registration has not occurred.</li>
 * </ul>
 * 
 * @param name The candidate metric's name.
 * @param docstring The docstring for the metric to help someone unfamiliar
 *        with it understand and develop an overview thereof within a few
 *        seconds of reading it.
 * @param baseLabels Verbatim labels that are embedded into the registered
 *        metric and displayed on exposition.
 * @param metric The metric to be registered.
 * @throws IllegalArgumentException,IllegalStateException if
 *         {@link #PROMETHEUS_CLIENT_ABORTONMISUSE} has been set to
 *         {@code TRUE} and invalid registrations have been provided.
 */
public void register(final String name, final String docstring, final Map<String, String> baseLabels,
        final Metric metric) {
    // XXX: Add expensive cross-validation of double-name registration,
    // defaulting to off.
    try {
        validateArguments(name, docstring, baseLabels);

        final ImmutableMap.Builder labelSetBuilder = new ImmutableMap.Builder();
        if (baseLabels != null) {
            labelSetBuilder.putAll(baseLabels);
        }
        labelSetBuilder.put(Reserved.NAME.label(), name);

        final Map<String, String> labelSet = labelSetBuilder.build();

        validateLabelSet(labelSet);

        baseLabelsToMetrics.put(labelSet, new Vector(labelSet, docstring, metric));
    } catch (final IllegalArgumentException e) {
        final String candidateValue = System.getProperty(PROMETHEUS_CLIENT_ABORTONMISUSE);
        log.error("Could not register {}...", name);
        if (!TRUE.equalsIgnoreCase(candidateValue)) {
            throw e;
        }
    } catch (final IllegalStateException e) {
        log.error("Could not register {}...", name);
        final String candidateValue = System.getProperty(PROMETHEUS_CLIENT_ABORTONMISUSE);
        if (!TRUE.equalsIgnoreCase(candidateValue)) {
            throw e;
        }
    }
}