Example usage for com.google.common.base Functions forMap

List of usage examples for com.google.common.base Functions forMap

Introduction

In this page you can find the example usage for com.google.common.base Functions forMap.

Prototype

public static <K, V> Function<K, V> forMap(Map<K, V> map) 

Source Link

Document

Returns a function which performs a map lookup.

Usage

From source file:com.music.MusicXmlRenderer.java

private static double getClosestLength(double length) {
    if (length == 0) {
        return 0;
    }/*  w ww  .  j a  v a 2s . c o m*/
    Map<Double, Double> proximity = new HashMap<>();
    for (double baseLength : LENGTHS) {
        if (baseLength == length) {
            return length;
        }
        for (SpecialNoteType type : SpecialNoteType.values()) {
            if (baseLength * type.getValue() == length) {
                return baseLength;
            }
        }
        if (length < baseLength && length * 1.2 >= baseLength) {
            return baseLength;
        }
        if (length > baseLength && length * 0.8 <= baseLength) {
            return baseLength;
        }
        proximity.put(baseLength, length > baseLength ? length / baseLength : baseLength / length);
    }
    return ImmutableSortedMap.copyOf(proximity, Ordering.natural().onResultOf(Functions.forMap(proximity)))
            .firstKey();
}

From source file:com.facebook.buck.android.relinker.NativeRelinker.java

public NativeRelinker(BuildRuleParams buildRuleParams, SourcePathResolver resolver,
        SourcePathRuleFinder ruleFinder, CxxBuckConfig cxxBuckConfig,
        ImmutableMap<TargetCpuType, NdkCxxPlatform> nativePlatforms,
        ImmutableMap<Pair<TargetCpuType, String>, SourcePath> linkableLibs,
        ImmutableMap<Pair<TargetCpuType, String>, SourcePath> linkableLibsAssets) {
    this.ruleFinder = ruleFinder;
    Preconditions.checkArgument(!linkableLibs.isEmpty() || !linkableLibsAssets.isEmpty(),
            "There should be at least one native library to relink.");

    this.buildRuleParams = buildRuleParams;
    this.resolver = resolver;
    this.cxxBuckConfig = cxxBuckConfig;
    this.nativePlatforms = nativePlatforms;

    /*/*from ww  w  . jav a2  s. c o m*/
    When relinking a library, any symbols needed by a (transitive) dependent must continue to be
    exported. As relinking one of those dependents may change the set of symbols that it needs,
    we only need to keep the symbols that are still used after a library is relinked. So, this
    relinking process basically works in the reverse order of the original link process. As each
    library is relinked, we now know the set of symbols that are needed in that library's
    dependencies.
            
    For linkables that can't be resolved to a BuildRule, we can't tell what libraries that one
    depends on. So, we essentially assume that everything depends on it.
    */

    ImmutableMap.Builder<BuildRule, Pair<TargetCpuType, SourcePath>> ruleMapBuilder = ImmutableMap.builder();
    ImmutableSet.Builder<Pair<TargetCpuType, SourcePath>> copiedLibraries = ImmutableSet.builder();

    for (Map.Entry<Pair<TargetCpuType, String>, SourcePath> entry : Iterables.concat(linkableLibs.entrySet(),
            linkableLibsAssets.entrySet())) {
        SourcePath source = entry.getValue();
        Optional<BuildRule> rule = ruleFinder.getRule(source);
        if (rule.isPresent()) {
            ruleMapBuilder.put(rule.get(), new Pair<>(entry.getKey().getFirst(), source));
        } else {
            copiedLibraries.add(new Pair<>(entry.getKey().getFirst(), source));
        }
    }

    ImmutableMap<BuildRule, Pair<TargetCpuType, SourcePath>> ruleMap = ruleMapBuilder.build();
    ImmutableSet<BuildRule> linkableRules = ruleMap.keySet();

    // Now, for every linkable build rule, we need to figure out all the other linkable build rules
    // that could depend on it (or rather, could use symbols from it).

    // This is the sub-graph that includes the linkableRules and all the dependents (including
    // non-linkable rules).
    final DirectedAcyclicGraph<BuildRule> graph = getBuildGraph(linkableRules);
    ImmutableList<BuildRule> sortedRules = TopologicalSort.sort(graph);
    // This maps a build rule to every rule in linkableRules that depends on it. This (added to the
    // copied libraries) is the set of linkables that could use a symbol from this build rule.
    ImmutableMap<BuildRule, ImmutableSet<BuildRule>> allDependentsMap = getAllDependentsMap(linkableRules,
            graph, sortedRules);

    ImmutableMap.Builder<SourcePath, SourcePath> pathMap = ImmutableMap.builder();

    // Create the relinker rules for the libraries that couldn't be resolved back to a base rule.
    ImmutableList.Builder<RelinkerRule> relinkRules = ImmutableList.builder();
    for (Pair<TargetCpuType, SourcePath> p : copiedLibraries.build()) {
        // TODO(cjhopman): We shouldn't really need a full RelinkerRule at this point. We know that we
        // are just going to copy it, we could just leave these libraries in place and only calculate
        // the list of needed symbols.
        TargetCpuType cpuType = p.getFirst();
        SourcePath source = p.getSecond();
        RelinkerRule relink = makeRelinkerRule(cpuType, source, ImmutableList.of());
        relinkRules.add(relink);
        pathMap.put(source, relink.getLibFileSourcePath());
    }
    ImmutableList<RelinkerRule> copiedLibrariesRules = relinkRules.build();

    // Process the remaining linkable rules in the reverse sorted order. This makes it easy to refer
    // to the RelinkerRules of dependents.
    Iterable<Pair<TargetCpuType, SourcePath>> sortedPaths = FluentIterable.from(sortedRules)
            .filter(linkableRules::contains).transform(Functions.forMap(ruleMap)).toList().reverse();
    Map<BuildRule, RelinkerRule> relinkerMap = new HashMap<>();

    for (Pair<TargetCpuType, SourcePath> p : sortedPaths) {
        TargetCpuType cpuType = p.getFirst();
        SourcePath source = p.getSecond();
        BuildRule baseRule = ruleFinder.getRuleOrThrow((BuildTargetSourcePath) source);
        // Relinking this library must keep any of the symbols needed by the libraries from the rules
        // in relinkerDeps.
        ImmutableList<RelinkerRule> relinkerDeps = ImmutableList.<RelinkerRule>builder()
                .addAll(copiedLibrariesRules)
                .addAll(Lists.transform(ImmutableList.copyOf(allDependentsMap.get(baseRule)),
                        Functions.forMap(relinkerMap)))
                .build();

        RelinkerRule relink = makeRelinkerRule(cpuType, source, relinkerDeps);
        relinkRules.add(relink);
        pathMap.put(source, relink.getLibFileSourcePath());
        relinkerMap.put(baseRule, relink);
    }

    Function<SourcePath, SourcePath> pathMapper = Functions.forMap(pathMap.build());
    rules = relinkRules.build();
    relinkedLibs = ImmutableMap.copyOf(Maps.transformValues(linkableLibs, pathMapper));
    relinkedLibsAssets = ImmutableMap.copyOf(Maps.transformValues(linkableLibsAssets, pathMapper));
}

From source file:org.eclipse.emf.compare.match.update.Updater.java

/**
 * Reorders the elements in oldValues so that their relative order matches the one of their equivalent in
 * newValues.//from www  .  ja  v a2s.c o m
 * <p>
 * We do this simply by sorting the oldValues list according to the index of the corresponding element in
 * the newValues list.
 */
private void reorderMatchingElements(EList<EObject> oldValues, EList<EObject> newValues,
        BiMap<EObject, EObject> matches) {
    Map<EObject, Integer> targetIndices = Maps.newHashMapWithExpectedSize(newValues.size());
    for (int i = 0; i < newValues.size(); i++) {
        targetIndices.put(newValues.get(i), i);
    }
    Function<EObject, Integer> matchingElementIndex = Functions.compose(Functions.forMap(targetIndices),
            Functions.forMap(matches));
    ECollections.sort(oldValues, Ordering.natural().onResultOf(matchingElementIndex));
}

From source file:com.ibm.bi.dml.runtime.transform.DummycodeAgent.java

public String constructDummycodedHeader(String header, Pattern delim) {

    if (_dcdList == null && _binList == null)
        // none of the columns are dummycoded, simply return the given header
        return header;

    String[] names = delim.split(header, -1);
    List<String> newNames = null;

    StringBuilder sb = new StringBuilder();

    // Dummycoding can be performed on either on a recoded column or on a binned column

    // process recoded columns
    if (_finalMapsCP != null && _dcdList != null) {
        for (int i = 0; i < _dcdList.length; i++) {
            int colID = _dcdList[i];
            HashMap<String, Long> map = _finalMapsCP.get(colID);
            String colName = UtilFunctions.unquote(names[colID - 1]);

            if (map != null) {
                // order map entries by their recodeID
                Ordering<String> valueComparator = Ordering.natural().onResultOf(Functions.forMap(map));
                newNames = valueComparator.sortedCopy(map.keySet());

                // construct concatenated string of map entries
                sb.setLength(0);/*w  w  w .ja  v  a 2  s. c  om*/
                for (int idx = 0; idx < newNames.size(); idx++) {
                    if (idx == 0)
                        sb.append(colName + DCD_NAME_SEP + newNames.get(idx));
                    else
                        sb.append(delim + colName + DCD_NAME_SEP + newNames.get(idx));
                }
                names[colID - 1] = sb.toString(); // replace original column name with dcd name
            }
        }
    } else if (_finalMaps != null && _dcdList != null) {
        for (int i = 0; i < _dcdList.length; i++) {
            int colID = _dcdList[i];
            HashMap<String, String> map = _finalMaps.get(colID);
            String colName = UtilFunctions.unquote(names[colID - 1]);

            if (map != null) {
                // order map entries by their recodeID (represented as Strings .. "1", "2", etc.)
                Ordering<String> orderByID = new Ordering<String>() {
                    public int compare(String s1, String s2) {
                        return (Integer.parseInt(s1) - Integer.parseInt(s2));
                    }
                };

                newNames = orderByID.onResultOf(Functions.forMap(map)).sortedCopy(map.keySet());
                // construct concatenated string of map entries
                sb.setLength(0);
                for (int idx = 0; idx < newNames.size(); idx++) {
                    if (idx == 0)
                        sb.append(colName + DCD_NAME_SEP + newNames.get(idx));
                    else
                        sb.append(delim + colName + DCD_NAME_SEP + newNames.get(idx));
                }
                names[colID - 1] = sb.toString(); // replace original column name with dcd name
            }
        }
    }

    // process binned columns
    if (_binList != null)
        for (int i = 0; i < _binList.length; i++) {
            int colID = _binList[i];

            // need to consider only binned and dummycoded columns
            if (isDummyCoded(colID) == -1)
                continue;

            int numBins = _numBins[i];
            String colName = UtilFunctions.unquote(names[colID - 1]);

            sb.setLength(0);
            for (int idx = 0; idx < numBins; idx++)
                if (idx == 0)
                    sb.append(colName + DCD_NAME_SEP + "Bin" + (idx + 1));
                else
                    sb.append(delim + colName + DCD_NAME_SEP + "Bin" + (idx + 1));
            names[colID - 1] = sb.toString(); // replace original column name with dcd name
        }

    // Construct the full header
    sb.setLength(0);
    for (int colID = 0; colID < names.length; colID++) {
        if (colID == 0)
            sb.append(names[colID]);
        else
            sb.append(delim + names[colID]);
    }
    //System.out.println("DummycodedHeader: " + sb.toString());

    return sb.toString();
}

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

/**
 * Returns a table of data for the given sets of fields and objects.  The table is row-keyed by
 * object and column-keyed by field, in the same iteration order as the provided sets.
 *///from   www .j  av a2  s  .  c o  m
private ImmutableTable<T, String, String> extractData(ImmutableSet<String> fields, ImmutableSet<T> objects) {
    ImmutableTable.Builder<T, String, String> builder = new ImmutableTable.Builder<>();
    for (T object : objects) {
        Map<String, Object> fieldMap = new HashMap<>();
        // Base case of the mapping is to use ImmutableObject's toDiffableFieldMap().
        fieldMap.putAll(object.toDiffableFieldMap());
        // Next, overlay any field-level overrides specified by the subclass.
        fieldMap.putAll(getFieldOverrides(object));
        // Next, add to the mapping all the aliases, with their values defined as whatever was in the
        // map under the aliased field's original name.
        fieldMap.putAll(Maps.transformValues(getFieldAliases(), Functions.forMap(new HashMap<>(fieldMap))));
        Set<String> expectedFields = ImmutableSortedSet.copyOf(fieldMap.keySet());
        for (String field : fields) {
            checkArgument(fieldMap.containsKey(field), "Field '%s' not found - recognized fields are:\n%s",
                    field, expectedFields);
            builder.put(object, field, Objects.toString(fieldMap.get(field), ""));
        }
    }
    return builder.build();
}

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

public TargetGraph createTargetGraph(DistBuildTargetGraphCodec codec) throws IOException {
    return codec.createTargetGraph(remoteState.getTargetGraph(), Functions.forMap(cells));
}

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

protected static OmnibusSpec buildSpec(final CxxPlatform cxxPlatform,
        final Iterable<? extends NativeLinkTarget> includedRoots,
        final Iterable<? extends NativeLinkable> excludedRoots) {

    // A map of targets to native linkable objects.  We maintain this, so that we index our
    // bookkeeping around `BuildTarget` and avoid having to guarantee that all other types are
    // hashable.//from  w  ww.j  ava 2s .c  om
    final Map<BuildTarget, NativeLinkable> nativeLinkables = new LinkedHashMap<>();

    // The nodes which should *not* be included in the omnibus link.
    final Set<BuildTarget> excluded = new LinkedHashSet<>();

    // Process all the roots included in the omnibus link.
    final Map<BuildTarget, NativeLinkTarget> roots = new LinkedHashMap<>();
    Map<BuildTarget, NativeLinkable> rootDeps = new LinkedHashMap<>();
    for (NativeLinkTarget root : includedRoots) {
        roots.put(root.getBuildTarget(), root);
        for (NativeLinkable dep : NativeLinkables.getNativeLinkables(cxxPlatform,
                root.getNativeLinkTargetDeps(cxxPlatform), Linker.LinkableDepType.SHARED).values()) {
            Linker.LinkableDepType linkStyle = NativeLinkables
                    .getLinkStyle(dep.getPreferredLinkage(cxxPlatform), Linker.LinkableDepType.SHARED);
            Preconditions.checkState(linkStyle != Linker.LinkableDepType.STATIC);

            // We only consider deps which aren't *only* statically linked.
            if (linkStyle == Linker.LinkableDepType.SHARED) {
                rootDeps.put(dep.getBuildTarget(), dep);
                nativeLinkables.put(dep.getBuildTarget(), dep);
            }
        }
    }

    // Process all roots excluded from the omnibus link, and add them to our running list of
    // excluded nodes.
    for (NativeLinkable root : excludedRoots) {
        nativeLinkables.put(root.getBuildTarget(), root);
        excluded.add(root.getBuildTarget());
    }

    // Perform the first walk starting from the native linkable nodes immediately reachable via the
    // included roots.  We'll accomplish two things here:
    // 1. Build up the map of node names to their native linkable objects.
    // 2. Perform an initial discovery of dependency nodes to exclude from the omnibus link.
    new AbstractBreadthFirstTraversal<BuildTarget>(rootDeps.keySet()) {
        @Override
        public ImmutableSet<BuildTarget> visit(BuildTarget target) {
            NativeLinkable nativeLinkable = Preconditions.checkNotNull(nativeLinkables.get(target));
            ImmutableMap<BuildTarget, NativeLinkable> deps = Maps
                    .uniqueIndex(getDeps(nativeLinkable, cxxPlatform), HasBuildTarget::getBuildTarget);
            nativeLinkables.putAll(deps);
            if (nativeLinkable.getPreferredLinkage(cxxPlatform) == NativeLinkable.Linkage.SHARED) {
                excluded.add(target);
            }
            return deps.keySet();
        }
    }.start();

    // Do another walk to flesh out the transitively excluded nodes.
    new AbstractBreadthFirstTraversal<BuildTarget>(excluded) {
        @Override
        public Iterable<BuildTarget> visit(BuildTarget target) {
            NativeLinkable nativeLinkable = Preconditions.checkNotNull(nativeLinkables.get(target));
            ImmutableMap<BuildTarget, NativeLinkable> deps = Maps
                    .uniqueIndex(getDeps(nativeLinkable, cxxPlatform), HasBuildTarget::getBuildTarget);
            nativeLinkables.putAll(deps);
            excluded.add(target);
            return deps.keySet();
        }
    }.start();

    // And then we can do one last walk to create the actual graph which contain only root and body
    // nodes to include in the omnibus link.
    final MutableDirectedGraph<BuildTarget> graphBuilder = new MutableDirectedGraph<>();
    final Set<BuildTarget> deps = new LinkedHashSet<>();
    new AbstractBreadthFirstTraversal<BuildTarget>(Sets.difference(rootDeps.keySet(), excluded)) {
        @Override
        public Iterable<BuildTarget> visit(BuildTarget target) {
            graphBuilder.addNode(target);
            Set<BuildTarget> keep = new LinkedHashSet<>();
            for (BuildTarget dep : Iterables.transform(getDeps(target, roots, nativeLinkables, cxxPlatform),
                    HasBuildTarget::getBuildTarget)) {
                if (excluded.contains(dep)) {
                    deps.add(dep);
                } else {
                    keep.add(dep);
                    graphBuilder.addEdge(target, dep);
                }
            }
            return keep;
        }
    }.start();
    DirectedAcyclicGraph<BuildTarget> graph = new DirectedAcyclicGraph<>(graphBuilder);

    // Since we add all undefined root symbols into the omnibus library, we also need to include
    // any excluded root deps as deps of omnibus, as they may fulfill these undefined symbols.
    // Also add any excluded nodes that are also root dependencies.
    deps.addAll(Sets.intersection(rootDeps.keySet(), excluded));

    return ImmutableOmnibusSpec.builder().graph(graph).roots(roots)
            .body(FluentIterable.from(graph.getNodes()).filter(Predicates.not(roots.keySet()::contains))
                    .toMap(Functions.forMap(nativeLinkables)))
            .deps(Maps.asMap(deps, Functions.forMap(nativeLinkables)))
            .excluded(Maps.asMap(excluded, Functions.forMap(nativeLinkables))).build();
}

From source file:com.searchbox.solr.CategoryLikeThis.java

@Override
public void handleRequestBody(SolrQueryRequest req, SolrQueryResponse rsp) throws Exception {
    numRequests++;/*  w  w w  .  j a  v  a2s.  c  om*/
    long startTime = System.currentTimeMillis();
    if (!keystate) {
        LOGGER.error(
                "License key failure, not performing clt query. Please email contact@searchbox.com for more information.");
        return;
    }

    try {
        SolrParams params = req.getParams();
        String senseField = params.get(SenseParams.SENSE_FIELD, SenseParams.DEFAULT_SENSE_FIELD);
        BooleanQuery catfilter = new BooleanQuery();
        // Set field flags
        ReturnFields returnFields = new SolrReturnFields(req);
        rsp.setReturnFields(returnFields);
        int flags = 0;
        if (returnFields.wantsScore()) {
            flags |= SolrIndexSearcher.GET_SCORES;
        }

        String defType = params.get(QueryParsing.DEFTYPE, QParserPlugin.DEFAULT_QTYPE);
        String q = params.get(CommonParams.Q);
        Query query = null;
        SortSpec sortSpec = null;
        List<Query> filters = new LinkedList<Query>();
        List<RealTermFreqVector> prototypetfs = new LinkedList<RealTermFreqVector>();

        try {
            if (q != null) {
                QParser parser = QParser.getParser(q, defType, req);
                query = parser.getQuery();
                sortSpec = parser.getSort(true);
            }

            String[] fqs = req.getParams().getParams(CommonParams.FQ);
            if (fqs != null && fqs.length != 0) {
                for (String fq : fqs) {
                    if (fq != null && fq.trim().length() != 0) {
                        QParser fqp = QParser.getParser(fq, null, req);
                        filters.add(fqp.getQuery());
                    }
                }
            }
        } catch (Exception e) {
            numErrors++;
            throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, e);
        }

        SolrIndexSearcher searcher = req.getSearcher();
        DocListAndSet cltDocs = null;

        // Parse Required Params
        // This will either have a single Reader or valid query
        Reader reader = null;
        try {
            if (q == null || q.trim().length() < 1) {
                Iterable<ContentStream> streams = req.getContentStreams();
                if (streams != null) {
                    Iterator<ContentStream> iter = streams.iterator();
                    if (iter.hasNext()) {
                        reader = iter.next().getReader();
                    }
                    if (iter.hasNext()) {
                        numErrors++;
                        throw new SolrException(SolrException.ErrorCode.BAD_REQUEST,
                                "SenseLikeThis does not support multiple ContentStreams");
                    }
                }
            }

            int start = params.getInt(CommonParams.START, 0);
            int rows = params.getInt(CommonParams.ROWS, 10);

            // Find documents SenseLikeThis - either with a reader or a query
            // --------------------------------------------------------------------------------
            if (reader != null) {
                numErrors++;
                throw new RuntimeException("SLT based on a reader is not yet implemented");
            } else if (q != null) {

                LOGGER.debug("Query for category:\t" + query);
                DocList match = searcher.getDocList(query, null, null, 0, 10, flags); // get first 10
                if (match.size() == 0) { // no docs to make prototype!
                    LOGGER.info("No documents found for prototype!");
                    rsp.add("response", new DocListAndSet());
                    return;
                }

                HashMap<String, Float> overallFreqMap = new HashMap<String, Float>();
                // Create the TF of blah blah blah
                DocIterator iterator = match.iterator();
                while (iterator.hasNext()) {
                    // do a MoreLikeThis query for each document in results
                    int id = iterator.nextDoc();
                    LOGGER.trace("Working on doc:\t" + id);
                    RealTermFreqVector rtv = new RealTermFreqVector(id, searcher.getIndexReader(), senseField);
                    for (int zz = 0; zz < rtv.getSize(); zz++) {
                        Float prev = overallFreqMap.get(rtv.getTerms()[zz]);
                        if (prev == null) {
                            prev = 0f;
                        }
                        overallFreqMap.put(rtv.getTerms()[zz], rtv.getFreqs()[zz] + prev);
                    }
                    prototypetfs.add(rtv);
                }

                List<String> sortedKeys = Ordering.natural().onResultOf(Functions.forMap(overallFreqMap))
                        .immutableSortedCopy(overallFreqMap.keySet());
                int keyiter = Math.min(sortedKeys.size() - 1, BooleanQuery.getMaxClauseCount() - 1);
                LOGGER.debug("I have this many terms:\t" + sortedKeys.size());
                LOGGER.debug("And i'm going to use this many:\t" + keyiter);
                for (; keyiter >= 0; keyiter--) {
                    TermQuery tq = new TermQuery(new Term(senseField, sortedKeys.get(keyiter)));
                    catfilter.add(tq, BooleanClause.Occur.SHOULD);
                }

            } else {
                numErrors++;
                throw new SolrException(SolrException.ErrorCode.BAD_REQUEST,
                        "CategoryLikeThis requires either a query (?q=) or text to find similar documents.");
            }

            LOGGER.debug("document filter is: \t" + catfilter);
            CategorizationBase model = new CategorizationBase(prototypetfs);
            CategoryQuery clt = CategoryQuery.CategoryQueryForDocument(catfilter, model,
                    searcher.getIndexReader(), senseField);
            DocSet filtered = searcher.getDocSet(filters);
            cltDocs = searcher.getDocListAndSet(clt, filtered, Sort.RELEVANCE, start, rows, flags);
        } finally {
            if (reader != null) {
                reader.close();
            }
        }

        if (cltDocs == null) {
            numEmpty++;
            cltDocs = new DocListAndSet(); // avoid NPE
        }
        rsp.add("response", cltDocs.docList);

        // maybe facet the results
        if (params.getBool(FacetParams.FACET, false)) {
            if (cltDocs.docSet == null) {
                rsp.add("facet_counts", null);
            } else {
                SimpleFacets f = new SimpleFacets(req, cltDocs.docSet, params);
                rsp.add("facet_counts", f.getFacetCounts());
            }
        }
    } catch (Exception e) {
        numErrors++;
    } finally {
        totalTime += System.currentTimeMillis() - startTime;
    }

}

From source file:com.palantir.ptoss.cinch.core.BindingContext.java

private Map<String, ObjectFieldMethod> indexBindableProperties(Function<PropertyDescriptor, Method> methodFn)
        throws IntrospectionException {
    final Map<ObjectFieldMethod, String> getterOfms = Maps.newHashMap();
    for (Field field : Sets.newHashSet(bindableModels.values())) {
        BeanInfo beanInfo = Introspector.getBeanInfo(field.getType());
        PropertyDescriptor[] props = beanInfo.getPropertyDescriptors();
        for (PropertyDescriptor descriptor : props) {
            Method method = methodFn.apply(descriptor);
            if (method == null) {
                continue;
            }//from ww w  . j av a2s .  c  om
            BindableModel model = getFieldObject(field, BindableModel.class);
            getterOfms.put(new ObjectFieldMethod(model, field, method), descriptor.getName());
        }
    }
    return dotIndex(getterOfms.keySet(), ObjectFieldMethod.TO_FIELD_NAME, Functions.forMap(getterOfms));
}

From source file:com.google.devtools.build.lib.rules.android.DexArchiveAspect.java

/**
 * Runs Jars in {@link JavaRuntimeJarProvider} through desugaring action if flag is set and adds
 * the result to {@code result}. Note that this cannot happen in a separate aspect because aspects
 * don't see providers added by other aspects executed on the same target.
 *//*from   www  .  j  a va  2 s  .  c om*/
private Function<Artifact, Artifact> desugarJarsIfRequested(ConfiguredTarget base, RuleContext ruleContext,
        ConfiguredAspect.Builder result) {
    if (!getAndroidConfig(ruleContext).desugarJava8()) {
        return Functions.identity();
    }
    Map<Artifact, Artifact> newlyDesugared = new HashMap<>();
    if (JavaCommon.isNeverLink(ruleContext)) {
        result.addProvider(AndroidRuntimeJarProvider.NEVERLINK);
        return Functions.forMap(newlyDesugared);
    }
    AndroidRuntimeJarProvider.Builder desugaredJars = new AndroidRuntimeJarProvider.Builder()
            .addTransitiveProviders(collectPrerequisites(ruleContext, AndroidRuntimeJarProvider.class));
    JavaRuntimeJarProvider jarProvider = base.getProvider(JavaRuntimeJarProvider.class);
    if (jarProvider != null) {
        // These are all transitive hjars of dependencies and hjar of the jar itself
        NestedSet<Artifact> compileTimeClasspath = base.getProvider(JavaCompilationArgsProvider.class) // aspect definition requires this
                .getRecursiveJavaCompilationArgs().getCompileTimeJars();
        // For android_* targets we need to honor their bootclasspath (nicer in general to do so)
        ImmutableList<Artifact> bootclasspath = getBootclasspath(base, ruleContext);

        boolean basenameClash = checkBasenameClash(jarProvider.getRuntimeJars());
        for (Artifact jar : jarProvider.getRuntimeJars()) {
            Artifact desugared = createDesugarAction(ruleContext, basenameClash, jar, bootclasspath,
                    compileTimeClasspath);
            newlyDesugared.put(jar, desugared);
            desugaredJars.addDesugaredJar(jar, desugared);
        }
    }
    result.addProvider(desugaredJars.build());
    return Functions.forMap(newlyDesugared);
}