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.lanternpowered.server.config.GlobalConfig.java

public Map<String, Predicate<InetAddress>> getIpSets() {
    return ImmutableMap.copyOf(Maps.transformValues(this.server.ipSets, Predicates::and));
}

From source file:org.jboss.capedwarf.blobstore.CapedwarfBlobstoreService.java

public Map<String, List<BlobInfo>> getBlobInfos(HttpServletRequest httpServletRequest) {
    return Maps.transformValues(getUploads(httpServletRequest), BLOB_LIST_KEY_TO_INFO_FN);
}

From source file:org.iternine.jeppetto.dao.mongodb.enhance.DBObjectUtil.java

private static Map<?, ?> fromMap(final Object source, final Class<?>... typeParameters) {
    if (DirtyableDBObjectMap.class.isAssignableFrom(source.getClass())) {
        return (Map<?, ?>) source;
    }//from  w w  w.j a va  2  s  .  com

    Function<Object, Object> valueFunction = fromObjectFunction(coalesceTypeParam(typeParameters, 1));

    if (String.class != coalesceTypeParam(typeParameters, 0)) {
        Function<Object, Object> keyFunction = fromObjectFunction(coalesceTypeParam(typeParameters, 0));
        Map<?, ?> sourceMap = (Map<?, ?>) source;
        DirtyableDBObjectMap converted = new DirtyableDBObjectMap();

        for (Map.Entry<?, ?> entry : sourceMap.entrySet()) {
            converted.put(keyFunction.apply(entry.getKey()), valueFunction.apply(entry.getValue()));
        }

        converted.markPersisted();

        return converted;
    } else {
        return new DirtyableDBObjectMap(Maps.transformValues((Map<?, ?>) source, valueFunction));
    }
}

From source file:org.jboss.capedwarf.blobstore.CapedwarfBlobstoreService.java

public Map<String, List<FileInfo>> getFileInfos(HttpServletRequest httpServletRequest) {
    return Maps.transformValues(getUploads(httpServletRequest), FILE_LIST_KEY_TO_INFO_FN);
}

From source file:google.registry.tools.server.ListObjectsAction.java

/** Converts the provided table of data to text, formatted using the provided column widths. */
private List<String> generateFormattedData(ImmutableTable<T, String, String> data,
        ImmutableMap<String, Integer> columnWidths) {
    Function<Map<String, String>, String> rowFormatter = makeRowFormatter(columnWidths);
    List<String> lines = new ArrayList<>();

    if (isHeaderRowInUse(data)) {
        // Add a row of headers (column names mapping to themselves).
        Map<String, String> headerRow = Maps.asMap(data.columnKeySet(), Functions.<String>identity());
        lines.add(rowFormatter.apply(headerRow));

        // Add a row of separator lines (column names mapping to '-' * column width).
        Map<String, String> separatorRow = Maps.transformValues(columnWidths, new Function<Integer, String>() {
            @Override/*from   w w w .j  a  v a 2 s.  c  o m*/
            public String apply(Integer width) {
                return Strings.repeat("-", width);
            }
        });
        lines.add(rowFormatter.apply(separatorRow));
    }

    // Add the actual data rows.
    for (Map<String, String> row : data.rowMap().values()) {
        lines.add(rowFormatter.apply(row));
    }

    return lines;
}

From source file:org.graylog2.security.ldap.LdapSettingsImpl.java

@Override
public void setGroupMapping(Map<String, String> mapping) {
    Map<String, String> internal;
    if (mapping == null) {
        internal = Collections.emptyMap();
    } else {/*  w  w w  . j ava  2 s.com*/
        // we store ids internally but external users use the group names
        try {
            final Map<String, Role> nameToRole = Maps.uniqueIndex(roleService.loadAll(),
                    Roles.roleToNameFunction());

            internal = Maps.newHashMap(Maps.transformValues(mapping, new Function<String, String>() {
                @Nullable
                @Override
                public String apply(@Nullable String groupName) {
                    if (groupName == null || !nameToRole.containsKey(groupName)) {
                        return null;
                    }
                    return nameToRole.get(groupName).getId();
                }
            }));
        } catch (NotFoundException e) {
            LOG.error("Unable to convert group names to ids", e);
            throw new IllegalStateException("Unable to convert group names to ids", e);
        }
    }

    // convert the group -> role_id map to a list of {"group" -> group, "role_id" -> roleid } maps
    fields.put(GROUP_MAPPING_LIST, internal.entrySet().stream().map(entry -> {
        Map<String, String> m = Maps.newHashMap();
        m.put(LDAP_GROUP_MAPPING_NAMEKEY, entry.getKey());
        m.put(LDAP_GROUP_MAPPING_ROLEKEY, entry.getValue());
        return m;
    }).collect(Collectors.toList()));
}

From source file:com.twitter.aurora.scheduler.http.SchedulerzJob.java

private static Map<String, SchedulingDetails> buildSchedulingTable(Iterable<IAssignedTask> tasks) {

    Map<Integer, ITaskConfig> byInstance = Maps
            .transformValues(Maps.uniqueIndex(tasks, Tasks.ASSIGNED_TO_INSTANCE_ID), Tasks.ASSIGNED_TO_INFO);
    Map<Integer, SchedulingDetails> detailsByInstance = Maps.transformValues(byInstance, CONFIG_TO_DETAILS);
    Multimap<SchedulingDetails, Integer> instancesByDetails = Multimaps
            .invertFrom(Multimaps.forMap(detailsByInstance), HashMultimap.<SchedulingDetails, Integer>create());
    Map<SchedulingDetails, String> instanceStringsByDetails = Maps.transformValues(instancesByDetails.asMap(),
            TransformationUtils.INSTANCES_TOSTRING);
    return HashBiMap.create(instanceStringsByDetails).inverse();
}

From source file:ninja.leaping.permissionsex.backend.memory.MemoryOptionSubjectData.java

@Override
public Map<Set<Entry<String, String>>, List<Entry<String, String>>> getAllParents() {
    return Maps.filterValues(
            Maps.transformValues(contexts, new Function<DataEntry, List<Map.Entry<String, String>>>() {
                @Nullable/* w  w w  .  j  av a2s  .  c om*/
                @Override
                public List<Map.Entry<String, String>> apply(@Nullable DataEntry dataEntry) {
                    return dataEntry == null ? null
                            : dataEntry.parents == null ? null
                                    : Lists.transform(dataEntry.parents, PARENT_TRANSFORM_FUNC);
                }
            }), Predicates.notNull());
}

From source file:com.facebook.buck.python.PythonTestDescription.java

@Override
public <A extends Arg> PythonTest createBuildRule(TargetGraph targetGraph, final BuildRuleParams params,
        final BuildRuleResolver resolver, final A args)
        throws HumanReadableException, NoSuchBuildTargetException {

    PythonPlatform pythonPlatform = pythonPlatforms.getValue(params.getBuildTarget())
            .orElse(pythonPlatforms.getValue(args.platform.<Flavor>map(ImmutableFlavor::of)
                    .orElse(pythonPlatforms.getFlavors().iterator().next())));
    CxxPlatform cxxPlatform = cxxPlatforms.getValue(params.getBuildTarget()).orElse(defaultCxxPlatform);
    SourcePathRuleFinder ruleFinder = new SourcePathRuleFinder(resolver);
    SourcePathResolver pathResolver = new SourcePathResolver(ruleFinder);
    Path baseModule = PythonUtil.getBasePath(params.getBuildTarget(), args.baseModule);
    Optional<ImmutableMap<BuildTarget, Version>> selectedVersions = targetGraph.get(params.getBuildTarget())
            .getSelectedVersions();//from   w w w .  j ava  2 s .co m

    ImmutableMap<Path, SourcePath> srcs = PythonUtil.getModules(params.getBuildTarget(), pathResolver, "srcs",
            baseModule, args.srcs, args.platformSrcs, pythonPlatform, args.versionedSrcs, selectedVersions);

    ImmutableMap<Path, SourcePath> resources = PythonUtil.getModules(params.getBuildTarget(), pathResolver,
            "resources", baseModule, args.resources, args.platformResources, pythonPlatform,
            args.versionedResources, selectedVersions);

    // Convert the passed in module paths into test module names.
    ImmutableSet.Builder<String> testModulesBuilder = ImmutableSet.builder();
    for (Path name : srcs.keySet()) {
        testModulesBuilder.add(PythonUtil.toModuleName(params.getBuildTarget(), name.toString()));
    }
    ImmutableSet<String> testModules = testModulesBuilder.build();

    // Construct a build rule to generate the test modules list source file and
    // add it to the build.
    BuildRule testModulesBuildRule = createTestModulesSourceBuildRule(params,
            getTestModulesListPath(params.getBuildTarget(), params.getProjectFilesystem()), testModules);
    resolver.addToIndex(testModulesBuildRule);

    String mainModule;
    if (args.mainModule.isPresent()) {
        mainModule = args.mainModule.get();
    } else {
        mainModule = PythonUtil.toModuleName(params.getBuildTarget(), getTestMainName().toString());
    }

    // Build up the list of everything going into the python test.
    PythonPackageComponents testComponents = PythonPackageComponents.of(ImmutableMap.<Path, SourcePath>builder()
            .put(getTestModulesListName(), new BuildTargetSourcePath(testModulesBuildRule.getBuildTarget()))
            .put(getTestMainName(), pythonBuckConfig.getPathToTestMain(params.getProjectFilesystem()))
            .putAll(srcs).build(), resources, ImmutableMap.of(), ImmutableSet.of(), args.zipSafe);
    PythonPackageComponents allComponents = PythonUtil.getAllComponents(params, resolver, pathResolver,
            ruleFinder, testComponents, pythonPlatform, cxxBuckConfig, cxxPlatform,
            args.linkerFlags.stream()
                    .map(MacroArg.toMacroArgFunction(PythonUtil.MACRO_HANDLER, params.getBuildTarget(),
                            params.getCellRoots(), resolver)::apply)
                    .collect(MoreCollectors.toImmutableList()),
            pythonBuckConfig.getNativeLinkStrategy(), args.preloadDeps);

    // Build the PEX using a python binary rule with the minimum dependencies.
    BuildRuleParams binaryParams = params.copyWithChanges(getBinaryBuildTarget(params.getBuildTarget()),
            Suppliers.ofInstance(PythonUtil.getDepsFromComponents(ruleFinder, allComponents)),
            Suppliers.ofInstance(ImmutableSortedSet.of()));
    PythonBinary binary = binaryDescription.createPackageRule(binaryParams, resolver, pathResolver, ruleFinder,
            pythonPlatform, cxxPlatform, mainModule, args.extension, allComponents, args.buildArgs,
            args.packageStyle.orElse(pythonBuckConfig.getPackageStyle()),
            PythonUtil.getPreloadNames(resolver, cxxPlatform, args.preloadDeps));
    resolver.addToIndex(binary);

    ImmutableList.Builder<Pair<Float, ImmutableSet<Path>>> neededCoverageBuilder = ImmutableList.builder();
    for (NeededCoverageSpec coverageSpec : args.neededCoverage) {
        BuildRule buildRule = resolver.getRule(coverageSpec.getBuildTarget());
        if (params.getDeps().contains(buildRule) && buildRule instanceof PythonLibrary) {
            PythonLibrary pythonLibrary = (PythonLibrary) buildRule;
            ImmutableSortedSet<Path> paths;
            if (coverageSpec.getPathName().isPresent()) {
                Path path = coverageSpec.getBuildTarget().getBasePath()
                        .resolve(coverageSpec.getPathName().get());
                if (!pythonLibrary.getSrcs(pythonPlatform).keySet().contains(path)) {
                    throw new HumanReadableException(
                            "%s: path %s specified in needed_coverage not found in target %s",
                            params.getBuildTarget(), path, buildRule.getBuildTarget());
                }
                paths = ImmutableSortedSet.of(path);
            } else {
                paths = ImmutableSortedSet.copyOf(pythonLibrary.getSrcs(pythonPlatform).keySet());
            }
            neededCoverageBuilder
                    .add(new Pair<Float, ImmutableSet<Path>>(coverageSpec.getNeededCoverageRatio(), paths));
        } else {
            throw new HumanReadableException(
                    "%s: needed_coverage requires a python library dependency. Found %s instead",
                    params.getBuildTarget(), buildRule);
        }
    }

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

    // Generate and return the python test rule, which depends on the python binary rule above.
    return new PythonTest(
            params.copyWithDeps(
                    Suppliers.ofInstance(ImmutableSortedSet.<BuildRule>naturalOrder()
                            .addAll(params.getDeclaredDeps().get()).add(binary).build()),
                    params.getExtraDeps()),
            pathResolver, ruleFinder, testEnv, binary, args.labels, neededCoverageBuilder.build(),
            args.testRuleTimeoutMs.map(Optional::of).orElse(defaultTestRuleTimeoutMs), args.contacts);
}

From source file:org.eclipse.emf.compare.rcp.ui.internal.structuremergeviewer.filters.impl.DifferenceFilterManager.java

/**
 * Store value in preferences./*from   w  ww  .  j a  v  a 2  s.  c  om*/
 * 
 * @param currentValue
 *            Value to store.
 * @param defaultConf
 *            Default value.
 */
private void storeInPreferences(Set<? extends IDifferenceFilter> currentValue,
        Set<? extends IDifferenceFilter> defaultConf, String prefKey) {
    if (currentValue != null && !currentValue.equals(defaultConf)) {
        Map<String, IDifferenceFilter> toStore = Maps.filterValues(Maps.transformValues(map, TO_FILTER),
                Predicates.in(currentValue));
        String preferenceValue = Joiner.on(ItemUtil.PREFERENCE_DELIMITER).join(toStore.keySet());
        preferenceStore.put(prefKey, preferenceValue);
    } else {
        preferenceStore.remove(prefKey);
    }
}