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:edu.harvard.med.screensaver.service.libraries.PlateUpdater.java

private void updatePrimaryPlateStatus(Copy copy) {
    Map<PlateStatus, Integer> statusCounts = Maps.transformValues(
            Multimaps.index(copy.getPlates().values(), Plate.ToStatus).asMap(), CollectionSize);
    PlateStatus primaryPlateStatus = Collections.max(statusCounts.entrySet(), plateStatusFrequencyComparator)
            .getKey();/*  w w  w.  j a  v a  2  s  .  c om*/
    copy.setPrimaryPlateStatus(primaryPlateStatus);
    copy.setPlatesAvailable(statusCounts.get(PlateStatus.AVAILABLE));
}

From source file:com.facebook.buck.android.resources.ExoResourcesRewriter.java

static ReferenceMapper rewriteResources(Path inputPath, Path primaryResources, Path exoResources)
        throws IOException {
    try (ApkZip apkZip = new ApkZip(inputPath)) {
        UsedResourcesFinder.ResourceClosure closure = UsedResourcesFinder.computePrimaryApkClosure(apkZip);
        ReferenceMapper resMapping = BringToFrontMapper.construct(ResTablePackage.APP_PACKAGE_ID,
                closure.idsByType);/*from  w w  w.  java 2 s.c  om*/
        // Rewrite the arsc.
        apkZip.getResourceTable().reassignIds(resMapping);
        // Update the references in xml files.
        for (ResourcesXml xml : apkZip.getResourcesXmls()) {
            xml.transformReferences(resMapping::map);
        }
        // Write the full (rearranged) resources to the exo resources.
        try (ResourcesZipBuilder zipBuilder = new ResourcesZipBuilder(exoResources)) {
            for (ZipEntry entry : apkZip.getEntries()) {
                addEntry(zipBuilder, entry.getName(), apkZip.getContent(entry.getName()),
                        entry.getMethod() == ZipEntry.STORED ? 0 : Deflater.BEST_COMPRESSION, false);
            }
        }
        // Then, slice out the resources needed for the primary apk.
        try (ResourcesZipBuilder zipBuilder = new ResourcesZipBuilder(primaryResources)) {
            ResourceTable primaryResourceTable = ResourceTable.slice(apkZip.getResourceTable(),
                    ImmutableMap.copyOf(Maps.transformValues(closure.idsByType, Set::size)));
            addEntry(zipBuilder, "resources.arsc", primaryResourceTable.serialize(),
                    apkZip.getEntry("resources.arsc").getMethod() == ZipEntry.STORED ? 0
                            : Deflater.BEST_COMPRESSION,
                    false);
            for (String path : RichStream.from(closure.files).sorted().toOnceIterable()) {
                ZipEntry entry = apkZip.getEntry(path);
                addEntry(zipBuilder, entry.getName(), apkZip.getContent(entry.getName()),
                        entry.getMethod() == ZipEntry.STORED ? 0 : Deflater.BEST_COMPRESSION, false);
            }
        }
        return resMapping;
    }
}

From source file:org.apache.aurora.scheduler.async.GcExecutorLauncher.java

private TaskInfo makeGcTask(String hostName, SlaveID slaveId) {
    Set<IScheduledTask> tasksOnHost = Storage.Util.weaklyConsistentFetchTasks(storage,
            Query.slaveScoped(hostName));

    tasksCreated.incrementAndGet();//w w w.  ja  v a2  s .c  om
    return makeGcTask(hostName, slaveId, settings.getGcExecutorPath().get(), uuidGenerator.get(),
            new AdjustRetainedTasks()
                    .setRetainedTasks(Maps.transformValues(Tasks.mapById(tasksOnHost), Tasks.GET_STATUS)));
}

From source file:com.twitter.common.application.modules.LocalServiceRegistry.java

/**
 * Launches the local services if not already launched, otherwise this is a no-op.
 *//*w  w  w.j a va2  s . c o  m*/
void ensureLaunched() {
    if (primarySocket == null) {
        ImmutableList.Builder<LocalService> builder = ImmutableList.builder();

        for (ServiceRunner runner : runnerProvider.get()) {
            try {
                LocalService service = runner.launch();
                builder.add(service);
                shutdownRegistry.addAction(service.shutdownCommand);
            } catch (LaunchException e) {
                throw new IllegalStateException("Failed to launch " + runner, e);
            }
        }

        List<LocalService> localServices = builder.build();
        Iterable<LocalService> primaries = Iterables.filter(localServices, IS_PRIMARY);
        switch (Iterables.size(primaries)) {
        case 0:
            primarySocket = Optional.absent();
            break;

        case 1:
            primarySocket = Optional.of(SERVICE_TO_SOCKET.apply(Iterables.getOnlyElement(primaries)));
            break;

        default:
            throw new IllegalArgumentException("More than one primary local service: " + primaries);
        }

        Iterable<LocalService> auxSinglyNamed = Iterables.concat(FluentIterable.from(localServices)
                .filter(Predicates.not(IS_PRIMARY)).transform(AUX_NAME_BREAKOUT));

        Map<String, LocalService> byName;
        try {
            byName = Maps.uniqueIndex(auxSinglyNamed, GET_NAME);
        } catch (IllegalArgumentException e) {
            throw new IllegalArgumentException("Auxiliary services with identical names.", e);
        }

        auxiliarySockets = ImmutableMap.copyOf(Maps.transformValues(byName, SERVICE_TO_SOCKET));
    }
}

From source file:com.android.tools.idea.gradle.project.GradleModuleImporter.java

@NotNull
public static Map<String, VirtualFile> getSubProjects(@NotNull final VirtualFile settingsGradle,
        Project destinationProject) {/*from  ww  w . ja v a2s.  c  om*/
    GradleSettingsFile settingsFile = new GradleSettingsFile(settingsGradle, destinationProject);
    Map<String, File> allProjects = settingsFile.getModulesWithLocation();
    return Maps.transformValues(allProjects, new ResolvePath(virtualToIoFile(settingsGradle.getParent())));
}

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

/**
 * Returns a copy of the map that contains all features with surrogate queries.
 * Dynamically added surrogates override registered surrogates and each feature will only appear once in the map. 
 * /*from   w  w  w.  ja  v a  2s .  c o m*/
 * @return a new copy of the map that contains all features with surrogate queries.
 * @deprecated use {@link #getAllSurrogateQueries()} instead
 */
@Deprecated
public Map<IInputKey, PQuery> getAllSurrogateQueryFQNMap() {
    Map<IInputKey, IProvider<PQuery>> allSurrogateQueries = Maps.newHashMap(registeredSurrogateQueryMap);
    allSurrogateQueries.putAll(dynamicSurrogateQueryMap);
    return Maps.transformValues(allSurrogateQueries, new ProvidedValueFunction());
}

From source file:io.crate.operation.scalar.cast.CastFunctionResolver.java

public static Map<DataType, String> tryFunctionsMap() {
    return Maps.transformValues(FUNCTION_MAP, TO_TRY_CAST_MAP);
}

From source file:org.onosproject.store.primitives.impl.PartitionedAsyncConsistentMap.java

@Override
public CompletableFuture<Boolean> prepare(MapTransaction<K, V> transaction) {

    Map<AsyncConsistentMap<K, V>, List<MapUpdate<K, V>>> updatesGroupedByMap = Maps.newIdentityHashMap();
    transaction.updates().forEach(update -> {
        AsyncConsistentMap<K, V> map = getMap(update.key());
        updatesGroupedByMap.computeIfAbsent(map, k -> Lists.newLinkedList()).add(update);
    });/*from   w  w  w. j av  a 2s. c om*/
    Map<AsyncConsistentMap<K, V>, MapTransaction<K, V>> transactionsByMap = Maps.transformValues(
            updatesGroupedByMap, list -> new MapTransaction<>(transaction.transactionId(), list));

    return Tools
            .allOf(transactionsByMap.entrySet().stream().map(e -> e.getKey().prepare(e.getValue()))
                    .collect(Collectors.toList()))
            .thenApply(list -> list.stream().reduce(Boolean::logicalAnd).orElse(true));
}

From source file:org.apache.hadoop.hive.metastore.utils.MetaStoreServerUtils.java

/**
 * We have a need to sanity-check the map before conversion from persisted objects to
 * metadata thrift objects because null values in maps will cause a NPE if we send
 * across thrift. Pruning is appropriate for most cases except for databases such as
 * Oracle where Empty strings are stored as nulls, in which case we need to handle that.
 * See HIVE-8485 for motivations for this.
 *///from w  w w  . j  av  a2  s .  c om
public static Map<String, String> trimMapNulls(Map<String, String> dnMap,
        boolean retrieveMapNullsAsEmptyStrings) {
    if (dnMap == null) {
        return null;
    }
    // Must be deterministic order map - see HIVE-8707
    //   => we use Maps.newLinkedHashMap instead of Maps.newHashMap
    if (retrieveMapNullsAsEmptyStrings) {
        // convert any nulls present in map values to empty strings - this is done in the case
        // of backing dbs like oracle which persist empty strings as nulls.
        return Maps.newLinkedHashMap(Maps.transformValues(dnMap, transFormNullsToEmptyString));
    } else {
        // prune any nulls present in map values - this is the typical case.
        return Maps.newLinkedHashMap(Maps.filterValues(dnMap, Predicates.notNull()));
    }
}

From source file:com.facebook.buck.core.graph.transformation.DefaultGraphTransformationEngine.java

@Override
public final <KeyType extends ComputeKey<ResultType>, ResultType extends ComputeResult> ImmutableMap<KeyType, ResultType> computeAllUnchecked(
        Set<KeyType> keys) {
    return ImmutableMap.copyOf(Maps.transformValues(computeAll(keys), Futures::getUnchecked));
}