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:org.jclouds.openstack.keystone.v2_0.suppliers.LocationIdToURIFromAccessForTypeAndVersion.java

@Override
public Map<String, Supplier<URI>> get() {
    FluentIterable<Service> services = FluentIterable.from(access.get()).filter(apiTypeEquals);
    if (services.toSet().size() == 0)
        throw new NoSuchElementException(
                String.format("apiType %s not found in catalog %s", apiType, services));

    Iterable<Endpoint> endpoints = concat(services);

    if (size(endpoints) == 0)
        throw new NoSuchElementException(
                String.format("no endpoints for apiType %s in services %s", apiType, services));

    boolean checkVersionId = any(endpoints, versionAware);

    Multimap<String, Endpoint> locationToEndpoints = index(endpoints, endpointToLocationId);
    Map<String, Endpoint> locationToEndpoint;
    if (checkVersionId && apiVersion != null) {
        locationToEndpoint = refineToVersionSpecificEndpoint(locationToEndpoints);
        if (locationToEndpoint.size() == 0)
            throw new NoSuchElementException(
                    String.format("no endpoints for apiType %s are of version %s, or version agnostic: %s",
                            apiType, apiVersion, locationToEndpoints));
    } else {/*from   ww w  . j  a  v a 2  s  . c om*/
        locationToEndpoint = firstEndpointInLocation(locationToEndpoints);
    }

    logger.debug("endpoints for apiType %s and version %s: %s", apiType, apiVersion, locationToEndpoints);
    return Maps.transformValues(locationToEndpoint, endpointToSupplierURI);
}

From source file:org.apache.james.jmap.model.SetMessagesRequest.java

public Map<MessageId, UpdateMessagePatch> buildUpdatePatches(UpdateMessagePatchConverter converter) {
    return Maps.transformValues(update, func -> func.apply(converter));
}

From source file:com.google.devtools.build.skyframe.AbstractSkyFunctionEnvironment.java

private <E1 extends Exception, E2 extends Exception, E3 extends Exception, E4 extends Exception, E5 extends Exception> Map<SkyKey, ValueOrException5<E1, E2, E3, E4, E5>> getValueOrExceptions(
        Iterable<SkyKey> depKeys, final Class<E1> exceptionClass1, final Class<E2> exceptionClass2,
        final Class<E3> exceptionClass3, final Class<E4> exceptionClass4, final Class<E5> exceptionClass5)
        throws InterruptedException {
    SkyFunctionException.validateExceptionType(exceptionClass1);
    SkyFunctionException.validateExceptionType(exceptionClass2);
    SkyFunctionException.validateExceptionType(exceptionClass3);
    SkyFunctionException.validateExceptionType(exceptionClass4);
    SkyFunctionException.validateExceptionType(exceptionClass5);
    Map<SkyKey, ValueOrUntypedException> valueOrExceptions = getValueOrUntypedExceptions(depKeys);
    for (ValueOrUntypedException voe : valueOrExceptions.values()) {
        SkyValue value = voe.getValue();
        if (value == null) {
            Exception e = voe.getException();
            if (e == null || (!exceptionClass1.isInstance(e) && !exceptionClass2.isInstance(e)
                    && !exceptionClass3.isInstance(e) && !exceptionClass4.isInstance(e)
                    && !exceptionClass5.isInstance(e))) {
                valuesMissing = true;/*  ww w  . java 2s.  c  om*/
                break;
            }
        }
    }
    // We transform the values directly to avoid the transient memory cost of creating a new map.
    return Maps.transformValues(valueOrExceptions,
            new Function<ValueOrUntypedException, ValueOrException5<E1, E2, E3, E4, E5>>() {
                @Override
                public ValueOrException5<E1, E2, E3, E4, E5> apply(ValueOrUntypedException voe) {
                    SkyValue value = voe.getValue();
                    if (value != null) {
                        return ValueOrExceptionUtils.<E1, E2, E3, E4, E5>ofValue(value);
                    }
                    Exception e = voe.getException();
                    if (e != null) {
                        if (exceptionClass1.isInstance(e)) {
                            return ValueOrExceptionUtils.<E1, E2, E3, E4, E5>ofExn1(exceptionClass1.cast(e));
                        }
                        if (exceptionClass2.isInstance(e)) {
                            return ValueOrExceptionUtils.<E1, E2, E3, E4, E5>ofExn2(exceptionClass2.cast(e));
                        }
                        if (exceptionClass3.isInstance(e)) {
                            return ValueOrExceptionUtils.<E1, E2, E3, E4, E5>ofExn3(exceptionClass3.cast(e));
                        }
                        if (exceptionClass4.isInstance(e)) {
                            return ValueOrExceptionUtils.<E1, E2, E3, E4, E5>ofExn4(exceptionClass4.cast(e));
                        }
                        if (exceptionClass5.isInstance(e)) {
                            return ValueOrExceptionUtils.<E1, E2, E3, E4, E5>ofExn5(exceptionClass5.cast(e));
                        }
                    }
                    return ValueOrExceptionUtils.<E1, E2, E3, E4, E5>ofNullValue();
                }
            });
}

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

@GET
@Path("/{name}/children")
@Produces(MediaType.APPLICATION_JSON)//from   ww  w  .j  a  va  2 s.  c o m
public void getRootChildren(@PathParam("name") String name, @Suspended AsyncResponse response) {
    getPrimitive(name).thenCompose(tree -> tree.getChildren(tree.root())).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.apache.aurora.scheduler.updater.JobDiff.java

/**
 * Calculates the diff necessary to change the current state of a job to the proposed state.
 *
 * @param taskStore Store to fetch the job's current state from.
 * @param job Job being diffed.//  w w  w  .  java 2s . com
 * @param proposedState Proposed state to move the job towards.
 * @param scope Instances to limit the diff to.
 * @return A diff of the current state compared with {@code proposedState}, within {@code scope}.
 */
public static JobDiff compute(TaskStore taskStore, IJobKey job, Map<Integer, ITaskConfig> proposedState,
        Set<IRange> scope) {

    Map<Integer, ITaskConfig> currentState = ImmutableMap.copyOf(Maps.transformValues(
            Maps.uniqueIndex(taskStore.fetchTasks(Query.jobScoped(job).active()), Tasks::getInstanceId),
            Tasks::getConfig));

    JobDiff diff = computeUnscoped(currentState, job, proposedState);
    if (scope.isEmpty()) {
        return diff;
    } else {
        Set<Integer> limit = Numbers.rangesToInstanceIds(scope);
        Map<Integer, ITaskConfig> replaced = ImmutableMap
                .copyOf(Maps.filterKeys(diff.getReplacedInstances(), Predicates.in(limit)));
        Set<Integer> replacements = ImmutableSet
                .copyOf(Sets.intersection(diff.getReplacementInstances(), limit));

        Set<Integer> unchangedIds = ImmutableSet.copyOf(Sets.difference(
                ImmutableSet.copyOf(Sets.difference(currentState.keySet(), replaced.keySet())), replacements));
        Map<Integer, ITaskConfig> unchanged = ImmutableMap
                .copyOf(Maps.filterKeys(currentState, Predicates.in(unchangedIds)));

        return new JobDiff(replaced, replacements, unchanged);
    }
}

From source file:ninja.leaping.permissionsex.backend.sql.SqlSubjectData.java

@Override
public ImmutableSubjectData clearOptions() {
    if (this.segments.isEmpty()) {
        return this;
    }/* w  ww  .  j  a v  a 2  s . c om*/

    Map<Set<Entry<String, String>>, Segment> newValue = Maps.transformValues(this.segments,
            dataEntry -> dataEntry == null ? null : dataEntry.withoutOptions());
    return newWithUpdate(newValue, createBulkUpdateFunc(newValue.keySet()));
}

From source file:org.onosproject.store.primitives.resources.impl.AtomixDocumentTreeState.java

protected Map<String, Versioned<byte[]>> getChildren(Commit<? extends GetChildren> commit) {
    try {// ww w.  ja  va2  s  .  com
        Map<String, Versioned<TreeNodeValue>> children = docTree.getChildren(commit.operation().path());
        return children == null ? null
                : Maps.newHashMap(Maps.transformValues(children, value -> value.map(TreeNodeValue::value)));
    } finally {
        commit.close();
    }
}

From source file:com.facebook.buck.distributed.DistBuildState.java

public static DistBuildState load(BuildJobState jobState, Cell rootCell,
        KnownBuildRuleTypesFactory knownBuildRuleTypesFactory) throws IOException {
    ProjectFilesystem rootCellFilesystem = rootCell.getFilesystem();

    ImmutableMap.Builder<Path, BuckConfig> cellConfigs = ImmutableMap.builder();
    ImmutableMap.Builder<Path, ProjectFilesystem> cellFilesystems = ImmutableMap.builder();
    ImmutableMap.Builder<Integer, Path> cellIndex = ImmutableMap.builder();

    Path sandboxPath = rootCellFilesystem.getRootPath()
            .resolve(rootCellFilesystem.getBuckPaths().getRemoteSandboxDir());
    rootCellFilesystem.mkdirs(sandboxPath);

    Path uniqueBuildRoot = Files.createTempDirectory(sandboxPath, "build");

    for (Map.Entry<Integer, BuildJobStateCell> remoteCellEntry : jobState.getCells().entrySet()) {
        BuildJobStateCell remoteCell = remoteCellEntry.getValue();

        Path cellRoot = uniqueBuildRoot.resolve(remoteCell.getNameHint());
        Files.createDirectories(cellRoot);

        Config config = createConfig(remoteCell.getConfig());
        ProjectFilesystem projectFilesystem = new ProjectFilesystem(cellRoot, config);
        BuckConfig buckConfig = createBuckConfig(config, projectFilesystem, remoteCell.getConfig());
        cellConfigs.put(cellRoot, buckConfig);
        cellFilesystems.put(cellRoot, projectFilesystem);
        cellIndex.put(remoteCellEntry.getKey(), cellRoot);
    }//from  ww w .j a v a  2 s  . c o  m

    CellProvider cellProvider = CellProvider.createForDistributedBuild(cellConfigs.build(),
            cellFilesystems.build(), knownBuildRuleTypesFactory);

    ImmutableBiMap<Integer, Cell> cells = ImmutableBiMap
            .copyOf(Maps.transformValues(cellIndex.build(), cellProvider::getCellByPath));
    return new DistBuildState(jobState, cells);
}

From source file:com.google.inject.internal.Annotations.java

/** Implements {@link Annotation#toString}. */
private static String annotationToString(Class<? extends Annotation> type, Map<String, Object> members)
        throws Exception {
    StringBuilder sb = new StringBuilder().append("@").append(type.getName()).append("(");
    JOINER.appendTo(sb, Maps.transformValues(members, DEEP_TO_STRING_FN));
    return sb.append(")").toString();
}

From source file:com.google.jenkins.flakyTestHandler.plugin.HistoryAggregatedFlakyTestResultAction.java

/**
 * Aggregate flaky runs one previous build and put results into a map between test name and
 * its map between scm revisions and aggregated flaky stats for that revision
 *
 * @param build the build to be aggregated
 *//* w  ww. j av a  2s . c om*/
public void aggregateOneBuild(AbstractBuild<?, ?> build) {
    FlakyTestResultAction action = build.getAction(FlakyTestResultAction.class);
    if (action == null) {
        return;
    }

    FlakyRunStats runStats = action.getFlakyRunStats();

    if (runStats == null) {
        return;
    }

    Map<String, SingleTestFlakyStatsWithRevision> testFlakyStatsMap = runStats
            .getTestFlakyStatsWithRevisionMap();

    if (testFlakyStatsMap == null) {
        // Skip old build which doesn't have the map
        return;
    }

    if (build.getCause(DeflakeCause.class) == null) {
        // This is a non-deflake build, update allTests
        allTests = testFlakyStatsMap.keySet();
    }

    for (Map.Entry<String, SingleTestFlakyStatsWithRevision> testFlakyStat : testFlakyStatsMap.entrySet()) {
        String testName = testFlakyStat.getKey();
        String revision = testFlakyStat.getValue().getRevision();
        SingleTestFlakyStats stats = testFlakyStat.getValue().getStats();

        if (aggregatedTestFlakyStatsWithRevision.containsKey(testName)) {
            Map<String, SingleTestFlakyStats> testFlakyStatMap = aggregatedTestFlakyStatsWithRevision
                    .get(testName);

            if (testFlakyStatMap.containsKey(revision)) {
                // Merge flaky stats with the same test and the same revision
                testFlakyStatMap.get(revision).merge(stats);
            } else {
                // First specific revision flaky stat for a given test
                testFlakyStatMap.put(revision, new SingleTestFlakyStats(stats));
            }
        } else {
            // The first test entry
            Map<String, SingleTestFlakyStats> testFlakyStatMap = new LinkedHashMap<String, SingleTestFlakyStats>();
            testFlakyStatMap.put(revision, new SingleTestFlakyStats(stats));
            aggregatedTestFlakyStatsWithRevision.put(testName, testFlakyStatMap);

        }
    }

    aggregatedFlakyStats = Maps.filterKeys(
            Maps.transformValues(aggregatedTestFlakyStatsWithRevision, REVISION_STATS_MAP_TO_AGGREGATED_STATS),
            Predicates.in(allTests));
}