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

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

Introduction

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

Prototype

@GwtIncompatible("NavigableMap")
public static <K, V1, V2> NavigableMap<K, V2> transformValues(NavigableMap<K, V1> fromMap,
        Function<? super V1, V2> function) 

Source Link

Document

Returns a view of a navigable map where each value is transformed by a function.

Usage

From source file:com.google.errorprone.refaster.UTemplater.java

/**
 * Returns a template based on a method. One-line methods starting with a {@code return} statement
 * are guessed to be expression templates, and all other methods are guessed to be block
 * templates./*from w  ww  .  ja  v a2s.  c  o m*/
 */
public static Template<?> createTemplate(Context context, MethodTree decl) {
    MethodSymbol declSym = ASTHelpers.getSymbol(decl);
    ImmutableClassToInstanceMap<Annotation> annotations = UTemplater.annotationMap(declSym);
    ImmutableMap<String, VarSymbol> freeExpressionVars = freeExpressionVariables(decl);
    Context subContext = new SubContext(context);
    final UTemplater templater = new UTemplater(freeExpressionVars, subContext);
    ImmutableMap<String, UType> expressionVarTypes = ImmutableMap
            .copyOf(Maps.transformValues(freeExpressionVars, new Function<VarSymbol, UType>() {
                @Override
                public UType apply(VarSymbol sym) {
                    return templater.template(sym.type);
                }
            }));

    UType genericType = templater.template(declSym.type);
    List<UTypeVar> typeParameters;
    UMethodType methodType;
    if (genericType instanceof UForAll) {
        UForAll forAllType = (UForAll) genericType;
        typeParameters = forAllType.getTypeVars();
        methodType = (UMethodType) forAllType.getQuantifiedType();
    } else if (genericType instanceof UMethodType) {
        typeParameters = ImmutableList.of();
        methodType = (UMethodType) genericType;
    } else {
        throw new IllegalArgumentException(
                "Expected genericType to be either a ForAll or a UMethodType, but was " + genericType);
    }

    List<? extends StatementTree> bodyStatements = decl.getBody().getStatements();
    if (bodyStatements.size() == 1 && Iterables.getOnlyElement(bodyStatements).getKind() == Kind.RETURN
            && context.get(REQUIRE_BLOCK_KEY) == null) {
        ExpressionTree expression = ((ReturnTree) Iterables.getOnlyElement(bodyStatements)).getExpression();
        return ExpressionTemplate.create(annotations, typeParameters, expressionVarTypes,
                templater.template(expression), methodType.getReturnType());
    } else {
        List<UStatement> templateStatements = new ArrayList<>();
        for (StatementTree statement : bodyStatements) {
            templateStatements.add(templater.template(statement));
        }
        return BlockTemplate.create(annotations, typeParameters, expressionVarTypes, templateStatements);
    }
}

From source file:uk.ac.open.kmi.iserve.discovery.disco.impl.GenericLogicDiscoverer.java

/**
 * Generic implementation for finding all the Services or Operations that have ALL the given types as inputs or outputs.
 *
 * @param entityType   the MSM URI of the type of entity we are looking for. Only supports Service and Operation.
 * @param relationship the MSM URI of the relationship we are looking for. Only supports hasInput and hasOutput.
 * @param types        the input/output types (modelReferences that is) we are looking for
 * @return a Map mapping operation/services URIs to MatchResults.
 *//*from   w w  w . ja v  a  2s .  c om*/
private Map<URI, MatchResult> findAll(URI entityType, URI relationship, Set<URI> types) {

    // Ensure that we have been given correct parameters
    if (types == null || types.isEmpty()
            || (!entityType.toASCIIString().equals(MSM.Service.getURI())
                    && !entityType.toASCIIString().equals(MSM.Operation.getURI()))
            || (!relationship.toASCIIString().equals(MSM.hasInput.getURI())
                    && !entityType.toASCIIString().equals(MSM.hasOutput.getURI())
                    && !relationship.toASCIIString().equals(SAWSDL.modelReference.getURI()))) {

        return ImmutableMap.of();
    }

    // Expand the input types to get all that match enough to be consumed
    // The structure is: <OriginalType, MatchingType, MatchResult>
    Table<URI, URI, MatchResult> expandedTypes;
    if (relationship.toASCIIString().equals(SAWSDL.modelReference.getURI())) {
        expandedTypes = HashBasedTable.create();
        for (URI type : types) {
            expandedTypes.putAll(this.conceptMatcher.listMatchesAtMostOfType(ImmutableSet.of(type),
                    LogicConceptMatchType.Subsume));
            expandedTypes.putAll(
                    this.conceptMatcher.listMatchesOfType(ImmutableSet.of(type), LogicConceptMatchType.Exact));
        }
    } else {
        expandedTypes = this.conceptMatcher.listMatchesAtLeastOfType(types, LogicConceptMatchType.Plugin);
    }

    // Track all the results in a multimap to push the details up the stack
    ListMultimap<URI, MatchResult> result = ArrayListMultimap.create();

    // Do the intersection of those operations that can consume each of the inputs separately
    boolean firstTime = true;
    Map<URI, MatchResult> intermediateMatches;
    Map<URI, Map<URI, MatchResult>> rowMap = expandedTypes.rowMap();
    // For each original type
    for (URI inputType : rowMap.keySet()) {
        // obtain those entities that match any of the expanded matching types
        intermediateMatches = findSome(entityType, relationship, rowMap.get(inputType).keySet());
        if (firstTime) {
            // Add all entries
            firstTime = false;
            for (Map.Entry<URI, MatchResult> entry : intermediateMatches.entrySet()) {
                result.put(entry.getKey(), entry.getValue());
            }
        } else {
            // Put all the values from the intersection
            Set<URI> intersection = Sets.intersection(result.keySet(), intermediateMatches.keySet());
            for (URI opUri : intersection) {
                result.put(opUri, intermediateMatches.get(opUri));
            }

            // Drop all the values from the difference
            // Use an immutable copy since the views will be changed
            Set<URI> difference = Sets.difference(result.keySet(), intermediateMatches.keySet())
                    .immutableCopy();
            for (URI opUri : difference) {
                result.removeAll(opUri);
            }
        }
    }

    // Merge the results into a single map using Union
    return Maps.transformValues(result.asMap(), MatchResultsMerger.INTERSECTION);

}

From source file:com.arpnetworking.utility.ParallelLeastShardAllocationStrategy.java

/**
 * {@inheritDoc}/*from   ww  w  .  j  a v a 2  s .c om*/
 */
@Override
public Future<Set<String>> rebalance(final Map<ActorRef, IndexedSeq<String>> currentShardAllocations,
        final Set<String> rebalanceInProgress) {
    // Only keep the rebalances that are in progress
    _pendingRebalances.keySet().retainAll(rebalanceInProgress);

    // Build a friendly set of current allocations
    // Sort the set by "effective shards after rebalance"
    final TreeSet<RegionShardAllocations> allocations = new TreeSet<>(
            Comparator.comparingInt(RegionShardAllocations::getEffectiveShardCount));

    for (final Map.Entry<ActorRef, IndexedSeq<String>> entry : currentShardAllocations.entrySet()) {
        allocations.add(new RegionShardAllocations(entry.getKey(),
                // Only count the shards that are not currently rebalancing
                JavaConversions.setAsJavaSet(entry.getValue().<String>toSet()).stream()
                        .filter(e -> !rebalanceInProgress.contains(e)).collect(Collectors.toSet())));
    }

    final Set<String> toRebalance = Sets.newHashSet();

    for (int x = 0; x < _maxParallel - rebalanceInProgress.size(); x++) {
        // Note: the poll* functions remove the item from the set
        final RegionShardAllocations leastShards = allocations.pollFirst();
        final RegionShardAllocations mostShards = allocations.pollLast();

        // Make sure that we have more than 1 region
        if (mostShards == null) {
            LOGGER.debug().setMessage("Cannot rebalance shards, less than 2 shard regions found.").log();
            break;
        }

        // Make sure that the difference is enough to warrant a rebalance
        if (mostShards.getEffectiveShardCount() - leastShards.getEffectiveShardCount() < _rebalanceThreshold) {
            LOGGER.debug().setMessage(
                    "Not rebalancing any (more) shards, shard region with most shards already balanced with least")
                    .addData("most", mostShards.getEffectiveShardCount())
                    .addData("least", leastShards.getEffectiveShardCount())
                    .addData("rebalanceThreshold", _rebalanceThreshold).log();
            break;
        }

        final String rebalanceShard = Iterables.get(mostShards.getShards(), 0);

        // Now we take a shard from mostShards and give it to leastShards
        mostShards.removeShard(rebalanceShard);
        leastShards.incrementIncoming();
        toRebalance.add(rebalanceShard);
        _pendingRebalances.put(rebalanceShard, leastShards.getRegion());

        // Put them back in the list with their new counts
        allocations.add(mostShards);
        allocations.add(leastShards);
    }

    // Transform the currentShardAllocations to a Map<ActorRef, Set<String>> from the
    // Scala representation
    final Map<ActorRef, Set<String>> currentAllocations = Maps.transformValues(currentShardAllocations,
            e -> Sets.newHashSet(JavaConversions.seqAsJavaList(e)));

    final RebalanceNotification notification = new RebalanceNotification(currentAllocations,
            rebalanceInProgress, _pendingRebalances);
    LOGGER.debug().setMessage("Broadcasting rebalance info").addData("target", _notify)
            .addData("shardAllocations", notification).log();
    if (_notify.isPresent()) {
        _notify.get().tell(notification, ActorRef.noSender());
    }
    return Futures.successful(toRebalance);
}

From source file:io.hops.transaction.context.BaseEntityContext.java

private Collection<Entity> filterValues(final State state, final boolean not) {
    Collection<Entity> entities = Maps.transformValues(contextEntities, new Function<ContextEntity, Entity>() {
        @Override/*from w  w  w.j a  v  a  2s.  c om*/
        public Entity apply(ContextEntity input) {
            if (not ? (input.getState() != state) : (input.getState() == state)) {
                return input.getEntity();
            }
            return null;
        }
    }).values();
    return Collections2.filter(entities, Predicates.notNull());
}

From source file:io.atomix.rest.resources.DocumentTreeResource.java

@GET
@Path("/{name}/children/{path: .*}")
@Produces(MediaType.APPLICATION_JSON)//from  w w  w  . j  a v  a  2 s.  c om
public void getChildren(@PathParam("name") String name, @PathParam("path") List<PathSegment> path,
        @Suspended AsyncResponse response) {
    getPrimitive(name).thenCompose(tree -> tree.getChildren(getDocumentPath(path)))
            .whenComplete((result, error) -> {
                if (error == null) {
                    response.resume(Response.ok(Maps.transformValues(result, VersionedResult::new)).build());
                } else {
                    LOGGER.warn("{}", error);
                    response.resume(Response.serverError().build());
                }
            });
}

From source file:org.eclipse.incquery.runtime.matchers.context.surrogate.SurrogateQueryRegistry.java

/**
 * @return the map of features with dynamically added surrogate query FQNs
 * @deprecated use {@link #getDynamicSurrogateQueries()} instead
 *//*from  w  w w. j  av a2 s  . c  o  m*/
public Map<IInputKey, PQuery> getDynamicSurrogateQueryFQNMap() {
    return Maps.transformValues(dynamicSurrogateQueryMap, new ProvidedValueFunction());
}

From source file:com.datatorrent.stram.util.LoggerUtil.java

public static ImmutableMap<String, String> getPatternLevels() {
    return ImmutableMap.copyOf(Maps.transformValues(patternLevel, levelToString));
}

From source file:com.facebook.presto.sql.planner.EffectivePredicateExtractor.java

private static TupleDomain<ColumnHandle> spanTupleDomain(TupleDomain<ColumnHandle> tupleDomain) {
    if (tupleDomain.isNone()) {
        return tupleDomain;
    }//from   ww w. jav  a  2 s  .  c o m

    // Simplify domains if they get too complex
    Map<ColumnHandle, Domain> spannedDomains = Maps.transformValues(tupleDomain.getDomains().get(),
            DomainUtils::simplifyDomain);

    return TupleDomain.withColumnDomains(spannedDomains);
}

From source file:com.facebook.buck.cxx.CxxTestDescription.java

@SuppressWarnings("PMD.PrematureDeclaration")
@Override// w  w  w .  j  a v  a  2  s  .  co m
public <A extends Arg> BuildRule createBuildRule(TargetGraph targetGraph, BuildRuleParams inputParams,
        final BuildRuleResolver resolver, final A args) throws NoSuchBuildTargetException {
    Optional<StripStyle> flavoredStripStyle = StripStyle.FLAVOR_DOMAIN.getValue(inputParams.getBuildTarget());
    Optional<LinkerMapMode> flavoredLinkerMapMode = LinkerMapMode.FLAVOR_DOMAIN
            .getValue(inputParams.getBuildTarget());
    inputParams = CxxStrip.removeStripStyleFlavorInParams(inputParams, flavoredStripStyle);
    inputParams = LinkerMapMode.removeLinkerMapModeFlavorInParams(inputParams, flavoredLinkerMapMode);
    final BuildRuleParams params = inputParams;

    Optional<CxxPlatform> platform = cxxPlatforms.getValue(params.getBuildTarget());
    CxxPlatform cxxPlatform = platform.orElse(defaultCxxPlatform);
    SourcePathRuleFinder ruleFinder = new SourcePathRuleFinder(resolver);
    SourcePathResolver pathResolver = new SourcePathResolver(ruleFinder);

    if (params.getBuildTarget().getFlavors().contains(CxxCompilationDatabase.COMPILATION_DATABASE)) {
        return CxxDescriptionEnhancer.createCompilationDatabase(params, resolver, pathResolver, ruleFinder,
                cxxBuckConfig, cxxPlatform, args);
    }

    if (params.getBuildTarget().getFlavors().contains(CxxCompilationDatabase.UBER_COMPILATION_DATABASE)) {
        return CxxDescriptionEnhancer.createUberCompilationDatabase(
                platform.isPresent() ? params : params.withFlavor(cxxPlatform.getFlavor()), resolver);
    }

    if (params.getBuildTarget().getFlavors().contains(CxxDescriptionEnhancer.SANDBOX_TREE_FLAVOR)) {
        return CxxDescriptionEnhancer.createSandboxTreeBuildRule(resolver, args, cxxPlatform, params);
    }

    // Generate the link rule that builds the test binary.
    final CxxLinkAndCompileRules cxxLinkAndCompileRules = CxxDescriptionEnhancer
            .createBuildRulesForCxxBinaryDescriptionArg(params, resolver, cxxBuckConfig, cxxPlatform, args,
                    flavoredStripStyle, flavoredLinkerMapMode);

    // Construct the actual build params we'll use, notably with an added dependency on the
    // CxxLink rule above which builds the test binary.
    BuildRuleParams testParams = params.appendExtraDeps(cxxLinkAndCompileRules.executable.getDeps(ruleFinder));
    testParams = CxxStrip.restoreStripStyleFlavorInParams(testParams, flavoredStripStyle);
    testParams = LinkerMapMode.restoreLinkerMapModeFlavorInParams(testParams, flavoredLinkerMapMode);

    // Supplier which expands macros in the passed in test environment.
    Supplier<ImmutableMap<String, String>> testEnv = () -> ImmutableMap
            .copyOf(Maps.transformValues(args.env, CxxDescriptionEnhancer.MACRO_HANDLER
                    .getExpander(params.getBuildTarget(), params.getCellRoots(), resolver)));

    // Supplier which expands macros in the passed in test arguments.
    Supplier<ImmutableList<String>> testArgs = () -> args.args.stream().map(CxxDescriptionEnhancer.MACRO_HANDLER
            .getExpander(params.getBuildTarget(), params.getCellRoots(), resolver)::apply)
            .collect(MoreCollectors.toImmutableList());

    Supplier<ImmutableSortedSet<BuildRule>> additionalDeps = () -> {
        ImmutableSortedSet.Builder<BuildRule> deps = ImmutableSortedSet.naturalOrder();

        // It's not uncommon for users to add dependencies onto other binaries that they run
        // during the test, so make sure to add them as runtime deps.
        deps.addAll(Sets.difference(params.getDeps(), cxxLinkAndCompileRules.getBinaryRule().getDeps()));

        // Add any build-time from any macros embedded in the `env` or `args` parameter.
        for (String part : Iterables.concat(args.args, args.env.values())) {
            try {
                deps.addAll(CxxDescriptionEnhancer.MACRO_HANDLER.extractBuildTimeDeps(params.getBuildTarget(),
                        params.getCellRoots(), resolver, part));
            } catch (MacroException e) {
                throw new HumanReadableException(e, "%s: %s", params.getBuildTarget(), e.getMessage());
            }
        }

        return deps.build();
    };

    CxxTest test;

    CxxTestType type = args.framework.orElse(getDefaultTestType());
    switch (type) {
    case GTEST: {
        test = new CxxGtestTest(testParams, pathResolver, ruleFinder, cxxLinkAndCompileRules.getBinaryRule(),
                cxxLinkAndCompileRules.executable, testEnv, testArgs,
                FluentIterable.from(args.resources)
                        .transform(SourcePaths.toSourcePath(params.getProjectFilesystem()))
                        .toSortedSet(Ordering.natural()),
                additionalDeps, args.labels, args.contacts, args.runTestSeparately.orElse(false),
                args.testRuleTimeoutMs.map(Optional::of).orElse(defaultTestRuleTimeoutMs),
                cxxBuckConfig.getMaximumTestOutputSize());
        break;
    }
    case BOOST: {
        test = new CxxBoostTest(testParams, pathResolver, ruleFinder, cxxLinkAndCompileRules.getBinaryRule(),
                cxxLinkAndCompileRules.executable, testEnv, testArgs,
                FluentIterable.from(args.resources)
                        .transform(SourcePaths.toSourcePath(params.getProjectFilesystem()))
                        .toSortedSet(Ordering.natural()),
                additionalDeps, args.labels, args.contacts, args.runTestSeparately.orElse(false),
                args.testRuleTimeoutMs.map(Optional::of).orElse(defaultTestRuleTimeoutMs));
        break;
    }
    default: {
        Preconditions.checkState(false, "Unhandled C++ test type: %s", type);
        throw new RuntimeException();
    }
    }

    return test;
}

From source file:org.jclouds.ec2.xml.CreateVolumeResponseHandler.java

@Override
public CreateVolumeResponseHandler setContext(HttpRequest request) {
    super.setContext(request);
    region = AWSUtils.findRegionInArgsOrNull(getRequest());
    if (region == null) {
        Set<String> zones = zonesSupplier.get();
        String zone = findAvailabilityZoneInArgsOrNull(getRequest(), zones);
        if (zone != null) {
            Map<String, Set<String>> regionToZones = Maps.transformValues(regionToZonesSupplier.get(),
                    Suppliers.<Set<String>>supplierFunction());
            for (Entry<String, Set<String>> entry : regionToZones.entrySet()) {
                if (entry.getValue().contains(zone)) {
                    region = entry.getKey();
                    break;
                }//from  ww  w . ja v  a2 s.  c o  m

            }
            checkNotNull(regionToZones, String.format("zone %s not in %s", zone, regionToZones));
        } else {
            region = defaultRegion.get();
        }
    }
    return this;
}