Example usage for com.google.common.collect ImmutableMap values

List of usage examples for com.google.common.collect ImmutableMap values

Introduction

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

Prototype

public ImmutableCollection<V> values() 

Source Link

Usage

From source file:com.facebook.buck.rules.CellProvider.java

/**
 * Create a cell provider at a given root.
 *///from   w  w w. j a  va 2  s  .com
public static CellProvider createForLocalBuild(ProjectFilesystem rootFilesystem, Watchman watchman,
        BuckConfig rootConfig, CellConfig rootCellConfigOverrides,
        KnownBuildRuleTypesFactory knownBuildRuleTypesFactory) throws IOException {

    DefaultCellPathResolver rootCellCellPathResolver = DefaultCellPathResolver
            .createWithConfigRepositoriesSection(rootFilesystem.getRootPath(),
                    rootConfig.getEntriesForSection(DefaultCellPathResolver.REPOSITORIES_SECTION));

    ImmutableMap<RelativeCellName, Path> transitiveCellPathMapping = rootCellCellPathResolver
            .getTransitivePathMapping();

    ImmutableMap<Path, RawConfig> pathToConfigOverrides;
    try {
        pathToConfigOverrides = rootCellConfigOverrides.getOverridesByPath(transitiveCellPathMapping);
    } catch (CellConfig.MalformedOverridesException e) {
        throw new HumanReadableException(e.getMessage());
    }

    ImmutableSet<Path> allRoots = ImmutableSet.copyOf(transitiveCellPathMapping.values());
    return new CellProvider(cellProvider -> new CacheLoader<Path, Cell>() {
        @Override
        public Cell load(Path cellPath) throws IOException, InterruptedException {
            cellPath = cellPath.toRealPath().normalize();

            Preconditions.checkState(allRoots.contains(cellPath),
                    "Cell %s outside of transitive closure of root cell (%s).", cellPath, allRoots);

            RawConfig configOverrides = Optional.ofNullable(pathToConfigOverrides.get(cellPath))
                    .orElse(RawConfig.of(ImmutableMap.of()));
            Config config = Configs.createDefaultConfig(cellPath, configOverrides);
            DefaultCellPathResolver cellPathResolver = new DefaultCellPathResolver(cellPath, config);
            ProjectFilesystem cellFilesystem = new ProjectFilesystem(cellPath, config);

            BuckConfig buckConfig = new BuckConfig(config, cellFilesystem, rootConfig.getArchitecture(),
                    rootConfig.getPlatform(), rootConfig.getEnvironment(), cellPathResolver);

            // TODO(13777679): cells in other watchman roots do not work correctly.

            return new Cell(cellPathResolver.getKnownRoots(), cellFilesystem, watchman, buckConfig,
                    knownBuildRuleTypesFactory, cellProvider);
        }
    }, cellProvider -> {
        try {
            return new Cell(rootCellCellPathResolver.getKnownRoots(), rootFilesystem, watchman, rootConfig,
                    knownBuildRuleTypesFactory, cellProvider);
        } catch (InterruptedException e) {
            throw new RuntimeException("Interrupted while loading root cell", e);
        } catch (IOException e) {
            throw new HumanReadableException("Failed to load root cell", e);
        }
    });
}

From source file:com.facebook.buck.features.haskell.HaskellDescriptionUtils.java

/** Give a rule that will result in a ghci session for the target */
public static HaskellGhciRule requireGhciRule(BuildTarget buildTarget, ProjectFilesystem projectFilesystem,
        BuildRuleParams params, CellPathResolver cellPathResolver, ActionGraphBuilder graphBuilder,
        HaskellPlatform platform, CxxBuckConfig cxxBuckConfig, ImmutableSortedSet<BuildTarget> argDeps,
        PatternMatchedCollection<ImmutableSortedSet<BuildTarget>> argPlatformDeps, SourceSortedSet argSrcs,
        ImmutableSortedSet<BuildTarget> argPreloadDeps,
        PatternMatchedCollection<ImmutableSortedSet<BuildTarget>> argPlatformPreloadDeps,
        ImmutableList<String> argCompilerFlags, Optional<BuildTarget> argGhciBinDep,
        Optional<SourcePath> argGhciInit, ImmutableList<SourcePath> argExtraScriptTemplates,
        boolean hsProfile) {
    SourcePathRuleFinder ruleFinder = new SourcePathRuleFinder(graphBuilder);
    SourcePathResolver pathResolver = DefaultSourcePathResolver.from(ruleFinder);

    ImmutableSet.Builder<BuildRule> depsBuilder = ImmutableSet.builder();
    depsBuilder.addAll(CxxDeps.builder().addDeps(argDeps).addPlatformDeps(argPlatformDeps).build()
            .get(graphBuilder, platform.getCxxPlatform()));
    ImmutableSet<BuildRule> deps = depsBuilder.build();

    ImmutableSet.Builder<BuildRule> preloadDepsBuilder = ImmutableSet.builder();
    preloadDepsBuilder.addAll(CxxDeps.builder().addDeps(argPreloadDeps).addPlatformDeps(argPlatformPreloadDeps)
            .build().get(graphBuilder, platform.getCxxPlatform()));
    ImmutableSet<BuildRule> preloadDeps = preloadDepsBuilder.build();

    // Haskell visitor
    ImmutableSet.Builder<HaskellPackage> haskellPackages = ImmutableSet.builder();
    ImmutableSet.Builder<HaskellPackage> prebuiltHaskellPackages = ImmutableSet.builder();
    ImmutableSet.Builder<HaskellPackage> firstOrderHaskellPackages = ImmutableSet.builder();
    AbstractBreadthFirstTraversal<BuildRule> haskellVisitor = new AbstractBreadthFirstTraversal<BuildRule>(
            deps) {/*from w ww . j a  va2 s. c o  m*/
        @Override
        public ImmutableSet<BuildRule> visit(BuildRule rule) {
            ImmutableSet.Builder<BuildRule> traverse = ImmutableSet.builder();
            if (rule instanceof HaskellLibrary || rule instanceof PrebuiltHaskellLibrary) {
                HaskellCompileDep haskellRule = (HaskellCompileDep) rule;
                HaskellCompileInput ci = haskellRule.getCompileInput(platform, Linker.LinkableDepType.STATIC,
                        hsProfile);

                if (params.getBuildDeps().contains(rule)) {
                    firstOrderHaskellPackages.addAll(ci.getPackages());
                }

                if (rule instanceof HaskellLibrary) {
                    haskellPackages.addAll(ci.getPackages());
                } else if (rule instanceof PrebuiltHaskellLibrary) {
                    prebuiltHaskellPackages.addAll(ci.getPackages());
                }

                traverse.addAll(haskellRule.getCompileDeps(platform));
            }

            return traverse.build();
        }
    };
    haskellVisitor.start();

    // Build the omnibus composition spec.
    HaskellGhciOmnibusSpec omnibusSpec = HaskellGhciDescription.getOmnibusSpec(buildTarget,
            platform.getCxxPlatform(), graphBuilder,
            NativeLinkables.getNativeLinkableRoots(
                    RichStream.from(deps).filter(NativeLinkable.class).toImmutableList(),
                    n -> n instanceof HaskellLibrary || n instanceof PrebuiltHaskellLibrary ? Optional.of(
                            n.getNativeLinkableExportedDepsForPlatform(platform.getCxxPlatform(), graphBuilder))
                            : Optional.empty()),
            // The preloaded deps form our excluded roots, which we need to keep them separate from
            // the omnibus library so that they can be `LD_PRELOAD`ed early.
            RichStream.from(preloadDeps).filter(NativeLinkable.class)
                    .collect(ImmutableMap.toImmutableMap(NativeLinkable::getBuildTarget, l -> l)));

    // Add an -rpath to the omnibus for shared library dependencies
    Path symlinkRelDir = HaskellGhciDescription.getSoLibsRelDir(buildTarget);
    ImmutableList.Builder<Arg> extraLinkFlags = ImmutableList.builder();
    extraLinkFlags.addAll(StringArg.from(Linkers.iXlinker("-rpath", String.format("%s/%s",
            platform.getCxxPlatform().getLd().resolve(graphBuilder).origin(), symlinkRelDir.toString()))));

    // Construct the omnibus shared library.
    BuildRule omnibusSharedObject = HaskellGhciDescription.requireOmnibusSharedObject(cellPathResolver,
            buildTarget, projectFilesystem, graphBuilder, platform.getCxxPlatform(), cxxBuckConfig,
            omnibusSpec.getBody().values(), omnibusSpec.getDeps().values(), extraLinkFlags.build());

    // Build up a map of all transitive shared libraries the the monolithic omnibus library depends
    // on (basically, stuff we couldn't statically link in).  At this point, this should *not* be
    // pulling in any excluded deps.
    SharedLibrariesBuilder sharedLibsBuilder = new SharedLibrariesBuilder();
    ImmutableMap<BuildTarget, NativeLinkable> transitiveDeps = NativeLinkables.getTransitiveNativeLinkables(
            platform.getCxxPlatform(), graphBuilder, omnibusSpec.getDeps().values());
    transitiveDeps.values().stream()
            // Skip statically linked libraries.
            .filter(l -> l.getPreferredLinkage(platform.getCxxPlatform(), graphBuilder) != Linkage.STATIC)
            .forEach(l -> sharedLibsBuilder.add(platform.getCxxPlatform(), l, graphBuilder));
    ImmutableSortedMap<String, SourcePath> sharedLibs = sharedLibsBuilder.build();

    // Build up a set of all transitive preload libs, which are the ones that have been "excluded"
    // from the omnibus link.  These are the ones we need to LD_PRELOAD.
    SharedLibrariesBuilder preloadLibsBuilder = new SharedLibrariesBuilder();
    omnibusSpec.getExcludedTransitiveDeps().values().stream()
            // Don't include shared libs for static libraries -- except for preload roots, which we
            // always link dynamically.
            .filter(l -> l.getPreferredLinkage(platform.getCxxPlatform(), graphBuilder) != Linkage.STATIC
                    || omnibusSpec.getExcludedRoots().containsKey(l.getBuildTarget()))
            .forEach(l -> preloadLibsBuilder.add(platform.getCxxPlatform(), l, graphBuilder));
    ImmutableSortedMap<String, SourcePath> preloadLibs = preloadLibsBuilder.build();

    HaskellSources srcs = HaskellSources.from(buildTarget, graphBuilder, pathResolver, ruleFinder, platform,
            "srcs", argSrcs);

    return HaskellGhciRule.from(buildTarget, projectFilesystem, params, ruleFinder, srcs, argCompilerFlags,
            argGhciBinDep.map(
                    target -> Objects.requireNonNull(graphBuilder.getRule(target).getSourcePathToOutput())),
            argGhciInit, omnibusSharedObject, sharedLibs, preloadLibs, firstOrderHaskellPackages.build(),
            haskellPackages.build(), prebuiltHaskellPackages.build(), hsProfile,
            platform.getGhciScriptTemplate().get(), argExtraScriptTemplates,
            platform.getGhciIservScriptTemplate().get(), platform.getGhciBinutils().get(),
            platform.getGhciGhc().get(), platform.getGhciIServ().get(), platform.getGhciIServProf().get(),
            platform.getGhciLib().get(), platform.getGhciCxx().get(), platform.getGhciCc().get(),
            platform.getGhciCpp().get(), platform.getGhciPackager().get());
}

From source file:com.google.polymer.JsRenamer.java

/**
 * Forwards renames to Polymer-relevant properties in the specified object map.
 * @param renameMap A mapping from symbol to renamed symbol.
 * @param objectMap A map of keys as property string names to values as nodes.
 *///from   w ww  . j  av  a 2  s .c  om
private static void renameObjectMap(ImmutableMap<String, String> renameMap,
        ImmutableMap<String, Node> objectMap) {
    // Rename 'computed' and 'observer' property description references.
    Node propertiesNode = objectMap.get("properties");
    if ((propertiesNode != null) && propertiesNode.isObjectLit()) {
        ImmutableMap<String, Node> propertiesMap = convertObjectLitNodeToMap(propertiesNode);
        for (Node propertyDescriptorNode : propertiesMap.values()) {
            if (propertyDescriptorNode.isObjectLit()) {
                ImmutableMap<String, Node> propertyDescriptorMap = convertObjectLitNodeToMap(
                        propertyDescriptorNode);
                renamePolymerJsStringNode(renameMap, propertyDescriptorMap.get("computed"));
                renamePolymerJsStringNode(renameMap, propertyDescriptorMap.get("observer"));
            }
        }
    }

    // Rename all JavaScript-like expressions in the 'observers' array.
    Node observersNode = objectMap.get("observers");
    if ((observersNode != null) && observersNode.isArrayLit()) {
        for (Node observerItem : observersNode.children()) {
            renamePolymerJsStringNode(renameMap, observerItem);
        }
    }

    // Rename all JavaScript-like expressions in the listeners descriptor.
    Node listenersNode = objectMap.get("listeners");
    if ((listenersNode != null) && listenersNode.isObjectLit()) {
        ImmutableMap<String, Node> listenersMap = convertObjectLitNodeToMap(listenersNode);
        for (Node listenerDescriptorNode : listenersMap.values()) {
            renamePolymerJsStringNode(renameMap, listenerDescriptorNode);
        }
    }

    // Rename the keyBindings string to method string map using in Polymer.IronA11yKeysBehavior.
    Node keyBindingsNode = objectMap.get("keyBindings");
    if ((keyBindingsNode != null) && keyBindingsNode.isObjectLit()) {
        renameKeyBindingsNode(renameMap, keyBindingsNode);
    }

    if (renameMap.containsKey("keyBindings")) {
        Node renamedKeyBindingsNode = objectMap.get(renameMap.get("keyBindings"));
        if ((renamedKeyBindingsNode != null) && renamedKeyBindingsNode.isObjectLit()) {
            renameKeyBindingsNode(renameMap, renamedKeyBindingsNode);
        }
    }
}

From source file:org.glowroot.agent.weaving.AdviceCache.java

private static ImmutableList<Advice> createReweavableAdvisors(List<InstrumentationConfig> reweavableConfigs,
        @Nullable Instrumentation instrumentation, File tmpDir, boolean cleanTmpDir) throws Exception {
    ImmutableMap<Advice, LazyDefinedClass> advisors = AdviceGenerator.createAdvisors(reweavableConfigs, null,
            false, true);/*w w w.  j a v a 2 s .c  o m*/
    if (instrumentation == null) {
        // instrumentation is null when debugging with LocalContainer
        ClassLoader isolatedWeavingClassLoader = Thread.currentThread().getContextClassLoader();
        checkNotNull(isolatedWeavingClassLoader);
        ClassLoaders.defineClasses(advisors.values(), isolatedWeavingClassLoader);
    } else {
        if (cleanTmpDir) {
            ClassLoaders.createDirectoryOrCleanPreviousContentsWithPrefix(tmpDir, "config-pointcuts");
        }
        if (!advisors.isEmpty()) {
            String suffix = "";
            int count = jarFileCounter.incrementAndGet();
            if (count > 1) {
                suffix = "-" + count;
            }
            File jarFile = new File(tmpDir, "config-pointcuts" + suffix + ".jar");
            ClassLoaders.defineClassesInBootstrapClassLoader(advisors.values(), instrumentation, jarFile);
        }
    }
    return advisors.keySet().asList();
}

From source file:com.facebook.buck.go.GoDescriptors.java

private static SymlinkTree makeSymlinkTree(BuildRuleParams params, SourcePathResolver pathResolver,
        SourcePathRuleFinder ruleFinder, ImmutableSet<GoLinkable> linkables) {
    ImmutableMap.Builder<Path, SourcePath> treeMapBuilder = ImmutableMap.builder();
    for (GoLinkable linkable : linkables) {
        for (Map.Entry<Path, SourcePath> linkInput : linkable.getGoLinkInput().entrySet()) {
            treeMapBuilder.put(getPathInSymlinkTree(pathResolver, linkInput.getKey(), linkInput.getValue()),
                    linkInput.getValue());
        }//from  w  w w  . j a v a2 s.c  o m
    }

    ImmutableMap<Path, SourcePath> treeMap;
    try {
        treeMap = treeMapBuilder.build();
    } catch (IllegalArgumentException ex) {
        throw new HumanReadableException(ex, "Multiple go targets have the same package name when compiling %s",
                params.getBuildTarget().getFullyQualifiedName());
    }

    params = params.appendExtraDeps(ruleFinder.filterBuildRuleInputs(treeMap.values()));

    Path root = BuildTargets.getScratchPath(params.getProjectFilesystem(), params.getBuildTarget(),
            "__%s__tree");

    return new SymlinkTree(params, pathResolver, root, treeMap);
}

From source file:org.fixb.meta.FixMetaScanner.java

private static <T> List<FixFieldMeta> processFields(final Class<T> model,
        final Optional<Constructor<T>> constructor, final MutableFixMetaDictionary dictionary) {
    final ImmutableMap<Integer, FixFieldMeta> fixFields = scanFields(model, dictionary);

    if (constructor.isPresent()) {
        final FixFieldMeta[] orderedFixFields = new FixFieldMeta[fixFields.size()];
        orderFixFields(constructor.get(), fixFields, orderedFixFields, dictionary, 0);
        return asList(orderedFixFields);
    } else {//from ww w  .  ja va  2  s .c  o m
        return new ArrayList<>(fixFields.values());
    }
}

From source file:edu.mit.streamjit.impl.compiler.Schedule.java

private static <T> Schedule<T> schedule(ImmutableSet<T> things,
        ImmutableSet<ExecutionConstraint<T>> executionConstraints,
        ImmutableSet<BufferingConstraint<T>> bufferingConstraints, int multiplier, int fireCost,
        int excessBufferCost) {
    ILPSolver solver = new ILPSolver();
    //There's one variable for each thing, which represents the number of
    //times it fires.  This uses the default bounds.  (TODO: perhaps a bound
    //at 1 if we're steady-state scheduling, maybe by marking things as
    //must-fire and marking the bottommost thing?)
    ImmutableMap.Builder<T, ILPSolver.Variable> variablesBuilder = ImmutableMap.builder();
    for (T thing : things)
        variablesBuilder.put(thing, solver.newVariable(thing.toString()));
    ImmutableMap<T, ILPSolver.Variable> variables = variablesBuilder.build();

    for (ExecutionConstraint<T> constraint : executionConstraints)
        solver.constrainAtLeast(variables.get(constraint.thing).asLinearExpr(1), constraint.minExecutions);

    HashMap<ILPSolver.Variable, Integer> sumOfConstraints = new HashMap<>();
    for (ILPSolver.Variable v : variables.values())
        sumOfConstraints.put(v, 0);// ww  w  .j  a v a 2 s.  c om
    for (BufferingConstraint<T> constraint : bufferingConstraints) {
        ILPSolver.Variable upstreamVar = variables.get(constraint.upstream),
                downstreamVar = variables.get(constraint.downstream);
        ILPSolver.LinearExpr expr = upstreamVar.asLinearExpr(constraint.pushRate).minus(constraint.popRate,
                downstreamVar);
        switch (constraint.condition) {
        case LESS_THAN_EQUAL:
            solver.constrainAtMost(expr, constraint.bufferDelta);
            break;
        case EQUAL:
            solver.constrainEquals(expr, constraint.bufferDelta);
            break;
        case GREATER_THAN_EQUAL:
            solver.constrainAtLeast(expr, constraint.bufferDelta);
            break;
        default:
            throw new AssertionError(constraint.condition);
        }

        sumOfConstraints.put(upstreamVar, sumOfConstraints.get(upstreamVar) + constraint.pushRate);
        sumOfConstraints.put(downstreamVar, sumOfConstraints.get(downstreamVar) - constraint.popRate);
    }

    //Add a special constraint to ensure at least one filter fires.
    //TODO: in init schedules we might not always need this...
    Iterator<ILPSolver.Variable> variablesIter = variables.values().iterator();
    ILPSolver.LinearExpr totalFirings = variablesIter.next().asLinearExpr(1);
    while (variablesIter.hasNext())
        totalFirings = totalFirings.plus(1, variablesIter.next());
    solver.constrainAtLeast(totalFirings, 1);

    for (ILPSolver.Variable v : variables.values())
        sumOfConstraints.put(v, sumOfConstraints.get(v) * excessBufferCost + fireCost);
    ILPSolver.ObjectiveFunction objFn = solver.minimize(
            solver.newLinearExpr(Maps.filterValues(sumOfConstraints, Predicates.not(Predicates.equalTo(0)))));

    try {
        solver.solve();
    } catch (SolverException ex) {
        throw new ScheduleException(ex);
    }

    ImmutableMap.Builder<T, Integer> schedule = ImmutableMap.builder();
    for (Map.Entry<T, ILPSolver.Variable> e : variables.entrySet())
        schedule.put(e.getKey(), e.getValue().value() * multiplier);
    return new Schedule<>(things, bufferingConstraints, schedule.build());
}

From source file:org.glowroot.agent.weaving.AnalyzedWorld.java

static List<Advice> mergeInstrumentationAnnotations(List<Advice> advisors, byte[] classBytes,
        @Nullable ClassLoader loader, String className) {
    byte[] marker = "Lorg/glowroot/agent/api/Instrumentation$".getBytes(UTF_8);
    if (Bytes.indexOf(classBytes, marker) == -1) {
        return advisors;
    }//from   w ww  .  ja va  2s. c o m
    InstrumentationSeekerClassVisitor cv = new InstrumentationSeekerClassVisitor();
    ClassReader cr = new ClassReader(classBytes);
    cr.accept(cv, ClassReader.SKIP_CODE);
    List<InstrumentationConfig> instrumentationConfigs = cv.getInstrumentationConfigs();
    if (instrumentationConfigs.isEmpty()) {
        return advisors;
    }
    if (loader == null) {
        logger.warn("@Instrumentation annotations not currently supported in bootstrap class" + " loader: {}",
                className);
        return advisors;
    }
    for (InstrumentationConfig instrumentationConfig : instrumentationConfigs) {
        instrumentationConfig.logValidationErrorsIfAny();
    }
    ImmutableMap<Advice, LazyDefinedClass> newAdvisors = AdviceGenerator.createAdvisors(instrumentationConfigs,
            null, false, false);
    try {
        ClassLoaders.defineClasses(newAdvisors.values(), loader);
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
    }
    List<Advice> mergedAdvisors = Lists.newArrayList(advisors);
    mergedAdvisors.addAll(newAdvisors.keySet());
    return mergedAdvisors;
}

From source file:com.googlecode.blaisemath.sketch.SketchActions.java

public static void alignHorizontal(Set<Graphic<Graphics2D>> selection) {
    Iterable<Graphic<Graphics2D>> sub = Iterables.filter(selection, MOVABLE_PREDICATE);
    if (Iterables.size(sub) < 2) {
        Logger.getLogger(SketchActions.class.getName()).log(Level.INFO,
                "Cannot align with fewer than 2 movable predicates.");
        return;/*  ww  w.  j a va2s.c om*/
    }
    ImmutableMap<Graphic<Graphics2D>, Point2D> locs = Maps.toMap(sub, LOC_FUNCTION);
    double yAvg = Points.average(locs.values()).getY();
    for (Graphic<Graphics2D> gr : sub) {
        setPrimitiveLocation((PrimitiveGraphicSupport<?, Graphics2D>) gr,
                new Point2D.Double(locs.get(gr).getX(), yAvg));
    }
}

From source file:com.googlecode.blaisemath.sketch.SketchActions.java

public static void alignVertical(Set<Graphic<Graphics2D>> selection) {
    Iterable<Graphic<Graphics2D>> sub = Iterables.filter(selection, MOVABLE_PREDICATE);
    if (Iterables.size(sub) < 2) {
        Logger.getLogger(SketchActions.class.getName()).log(Level.INFO,
                "Cannot align with fewer than 2 movable predicates.");
        return;/*w w w. j a  v  a  2 s  .  c  om*/
    }
    ImmutableMap<Graphic<Graphics2D>, Point2D> locs = Maps.toMap(sub, LOC_FUNCTION);
    double xAvg = Points.average(locs.values()).getY();
    for (Graphic<Graphics2D> gr : sub) {
        setPrimitiveLocation((PrimitiveGraphicSupport<?, Graphics2D>) gr,
                new Point2D.Double(xAvg, locs.get(gr).getY()));
    }
}