Example usage for com.google.common.collect MultimapBuilder treeKeys

List of usage examples for com.google.common.collect MultimapBuilder treeKeys

Introduction

In this page you can find the example usage for com.google.common.collect MultimapBuilder treeKeys.

Prototype

@SuppressWarnings("rawtypes")
public static MultimapBuilderWithKeys<Comparable> treeKeys() 

Source Link

Document

Uses a naturally-ordered TreeMap to map keys to value collections.

Usage

From source file:com.proofpoint.reporting.PrometheusCollector.java

Multimap<String, TaggedValue> collectData() {
    Multimap<String, TaggedValue> valuesByMetric = MultimapBuilder.treeKeys().treeSetValues().build();

    for (RegistrationInfo registrationInfo : reportedBeanRegistry.getReportedBeans()) {
        StringBuilder nameBuilder = new StringBuilder();
        if (registrationInfo.isApplicationPrefix()) {
            nameBuilder.append(applicationPrefix);
        }// w ww.  j av a  2 s. c  o  m
        nameBuilder.append(sanitizeMetricName(registrationInfo.getNamePrefix()));

        for (PrometheusBeanAttribute attribute : registrationInfo.getReportedBean().getPrometheusAttributes()) {
            String metricName = sanitizeMetricName(attribute.getName());
            String name;
            if ("".equals(metricName)) {
                name = nameBuilder.toString();
            } else {
                name = nameBuilder + "_" + metricName;
            }
            if (INITIAL_DIGIT_PATTERN.matcher(name).lookingAt()) {
                name = "_" + name;
            }
            ValueAndTimestamp valueAndTimestamp = null;

            try {
                valueAndTimestamp = attribute.getValue(null);
            } catch (MBeanException | ReflectionException ignored) {
            }

            if (valueAndTimestamp != null) {
                valuesByMetric.put(name, taggedValue(registrationInfo.getTags(), valueAndTimestamp));
            }
        }
    }
    valuesByMetric.put("ReportCollector_NumMetrics",
            taggedValue(versionTags, valueAndTimestamp(simplePrometheusValue(valuesByMetric.size()), null)));
    if (bucketIdProvider.get().getTimestamp() < startupTimestamp + TimeUnit.MINUTES.toMillis(10)) {
        valuesByMetric.put("ReportCollector_ServerStart",
                taggedValue(versionTags, valueAndTimestamp(simplePrometheusValue(1), startupTimestamp)));
    }
    return valuesByMetric;
}

From source file:io.prestosql.plugin.accumulo.index.ColumnCardinalityCache.java

/**
 * Gets the cardinality for each {@link AccumuloColumnConstraint}.
 * Given constraints are expected to be indexed! Who knows what would happen if they weren't!
 *
 * @param schema Schema name//from w w w. ja  va2  s .c o m
 * @param table Table name
 * @param auths Scan authorizations
 * @param idxConstraintRangePairs Mapping of all ranges for a given constraint
 * @param earlyReturnThreshold Smallest acceptable cardinality to return early while other tasks complete
 * @param pollingDuration Duration for polling the cardinality completion service
 * @return An immutable multimap of cardinality to column constraint, sorted by cardinality from smallest to largest
 * @throws TableNotFoundException If the metrics table does not exist
 * @throws ExecutionException If another error occurs; I really don't even know anymore.
 */
public Multimap<Long, AccumuloColumnConstraint> getCardinalities(String schema, String table,
        Authorizations auths, Multimap<AccumuloColumnConstraint, Range> idxConstraintRangePairs,
        long earlyReturnThreshold, Duration pollingDuration) {
    // Submit tasks to the executor to fetch column cardinality, adding it to the Guava cache if necessary
    CompletionService<Pair<Long, AccumuloColumnConstraint>> executor = new ExecutorCompletionService<>(
            executorService);
    idxConstraintRangePairs.asMap().forEach((key, value) -> executor.submit(() -> {
        long cardinality = getColumnCardinality(schema, table, auths, key.getFamily(), key.getQualifier(),
                value);
        LOG.debug("Cardinality for column %s is %s", key.getName(), cardinality);
        return Pair.of(cardinality, key);
    }));

    // Create a multi map sorted by cardinality
    ListMultimap<Long, AccumuloColumnConstraint> cardinalityToConstraints = MultimapBuilder.treeKeys()
            .arrayListValues().build();
    try {
        boolean earlyReturn = false;
        int numTasks = idxConstraintRangePairs.asMap().entrySet().size();
        do {
            // Sleep for the polling duration to allow concurrent tasks to run for this time
            Thread.sleep(pollingDuration.toMillis());

            // Poll each task, retrieving the result if it is done
            for (int i = 0; i < numTasks; ++i) {
                Future<Pair<Long, AccumuloColumnConstraint>> futureCardinality = executor.poll();
                if (futureCardinality != null && futureCardinality.isDone()) {
                    Pair<Long, AccumuloColumnConstraint> columnCardinality = futureCardinality.get();
                    cardinalityToConstraints.put(columnCardinality.getLeft(), columnCardinality.getRight());
                }
            }

            // If the smallest cardinality is present and below the threshold, set the earlyReturn flag
            Optional<Entry<Long, AccumuloColumnConstraint>> smallestCardinality = cardinalityToConstraints
                    .entries().stream().findFirst();
            if (smallestCardinality.isPresent()) {
                if (smallestCardinality.get().getKey() <= earlyReturnThreshold) {
                    LOG.info("Cardinality %s, is below threshold. Returning early while other tasks finish",
                            smallestCardinality);
                    earlyReturn = true;
                }
            }
        } while (!earlyReturn && cardinalityToConstraints.entries().size() < numTasks);
    } catch (ExecutionException | InterruptedException e) {
        if (e instanceof InterruptedException) {
            Thread.currentThread().interrupt();
        }
        throw new PrestoException(UNEXPECTED_ACCUMULO_ERROR, "Exception when getting cardinality", e);
    }

    // Create a copy of the cardinalities
    return ImmutableMultimap.copyOf(cardinalityToConstraints);
}

From source file:com.facebook.presto.accumulo.index.ColumnCardinalityCache.java

/**
 * Gets the cardinality for each {@link AccumuloColumnConstraint}.
 * Given constraints are expected to be indexed! Who knows what would happen if they weren't!
 *
 * @param schema Schema name/*w  ww. java  2s  .c  o  m*/
 * @param table Table name
 * @param auths Scan authorizations
 * @param idxConstraintRangePairs Mapping of all ranges for a given constraint
 * @param earlyReturnThreshold Smallest acceptable cardinality to return early while other tasks complete
 * @param pollingDuration Duration for polling the cardinality completion service
 * @return An immutable multimap of cardinality to column constraint, sorted by cardinality from smallest to largest
 * @throws TableNotFoundException If the metrics table does not exist
 * @throws ExecutionException If another error occurs; I really don't even know anymore.
 */
public Multimap<Long, AccumuloColumnConstraint> getCardinalities(String schema, String table,
        Authorizations auths, Multimap<AccumuloColumnConstraint, Range> idxConstraintRangePairs,
        long earlyReturnThreshold, Duration pollingDuration) throws ExecutionException, TableNotFoundException {
    // Submit tasks to the executor to fetch column cardinality, adding it to the Guava cache if necessary
    CompletionService<Pair<Long, AccumuloColumnConstraint>> executor = new ExecutorCompletionService<>(
            executorService);
    idxConstraintRangePairs.asMap().forEach((key, value) -> executor.submit(() -> {
        long cardinality = getColumnCardinality(schema, table, auths, key.getFamily(), key.getQualifier(),
                value);
        LOG.debug("Cardinality for column %s is %s", key.getName(), cardinality);
        return Pair.of(cardinality, key);
    }));

    // Create a multi map sorted by cardinality
    ListMultimap<Long, AccumuloColumnConstraint> cardinalityToConstraints = MultimapBuilder.treeKeys()
            .arrayListValues().build();
    try {
        boolean earlyReturn = false;
        int numTasks = idxConstraintRangePairs.asMap().entrySet().size();
        do {
            // Sleep for the polling duration to allow concurrent tasks to run for this time
            Thread.sleep(pollingDuration.toMillis());

            // Poll each task, retrieving the result if it is done
            for (int i = 0; i < numTasks; ++i) {
                Future<Pair<Long, AccumuloColumnConstraint>> futureCardinality = executor.poll();
                if (futureCardinality != null && futureCardinality.isDone()) {
                    Pair<Long, AccumuloColumnConstraint> columnCardinality = futureCardinality.get();
                    cardinalityToConstraints.put(columnCardinality.getLeft(), columnCardinality.getRight());
                }
            }

            // If the smallest cardinality is present and below the threshold, set the earlyReturn flag
            Optional<Entry<Long, AccumuloColumnConstraint>> smallestCardinality = cardinalityToConstraints
                    .entries().stream().findFirst();
            if (smallestCardinality.isPresent()) {
                if (smallestCardinality.get().getKey() <= earlyReturnThreshold) {
                    LOG.info("Cardinality %s, is below threshold. Returning early while other tasks finish",
                            smallestCardinality);
                    earlyReturn = true;
                }
            }
        } while (!earlyReturn && cardinalityToConstraints.entries().size() < numTasks);
    } catch (ExecutionException | InterruptedException e) {
        if (e instanceof InterruptedException) {
            Thread.currentThread().interrupt();
        }
        throw new PrestoException(UNEXPECTED_ACCUMULO_ERROR, "Exception when getting cardinality", e);
    }

    // Create a copy of the cardinalities
    return ImmutableMultimap.copyOf(cardinalityToConstraints);
}

From source file:org.glowroot.agent.live.ClasspathCache.java

synchronized void updateCache() {
    Multimap<String, Location> newClassNameLocations = HashMultimap.create();
    for (ClassLoader loader : getKnownClassLoaders()) {
        updateCache(loader, newClassNameLocations);
    }//from  w ww .j  a  v  a2  s .  c  om
    updateCacheWithClasspathClasses(newClassNameLocations);
    updateCacheWithBootstrapClasses(newClassNameLocations);
    if (!newClassNameLocations.isEmpty()) {
        // multimap that sorts keys and de-dups values while maintains value ordering
        SetMultimap<String, Location> newMap = MultimapBuilder.treeKeys().linkedHashSetValues().build();
        newMap.putAll(classNameLocations);
        newMap.putAll(newClassNameLocations);
        classNameLocations = ImmutableMultimap.copyOf(newMap);
    }
}

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

private static RuleConfiguredTargetBuilder init(RuleContext ruleContext,
        NestedSetBuilder<Artifact> filesBuilder, ResourceDependencies resourceDeps, JavaCommon javaCommon,
        AndroidCommon androidCommon, JavaSemantics javaSemantics, AndroidSemantics androidSemantics)
        throws InterruptedException, RuleErrorException {

    if (getMultidexMode(ruleContext) != MultidexMode.LEGACY
            && ruleContext.attributes().isAttributeValueExplicitlySpecified("main_dex_proguard_specs")) {
        ruleContext.throwWithAttributeError("main_dex_proguard_specs", "The "
                + "'main_dex_proguard_specs' attribute is only allowed if 'multidex' is set to 'legacy'");
    }// www . j  a va2 s .c  o m

    if (ruleContext.attributes().isAttributeValueExplicitlySpecified("proguard_apply_mapping")
            && ruleContext.attributes().get(ProguardHelper.PROGUARD_SPECS, BuildType.LABEL_LIST).isEmpty()) {
        ruleContext.throwWithAttributeError("proguard_apply_mapping",
                "'proguard_apply_mapping' can only be used when 'proguard_specs' is also set");
    }

    if (ruleContext.attributes().isAttributeValueExplicitlySpecified("rex_package_map")
            && !ruleContext.attributes().get("rewrite_dexes_with_rex", Type.BOOLEAN)) {
        ruleContext.throwWithAttributeError("rex_package_map",
                "'rex_package_map' can only be used when 'rewrite_dexes_with_rex' is also set");
    }

    if (ruleContext.attributes().isAttributeValueExplicitlySpecified("rex_package_map")
            && ruleContext.attributes().get(ProguardHelper.PROGUARD_SPECS, BuildType.LABEL_LIST).isEmpty()) {
        ruleContext.throwWithAttributeError("rex_package_map",
                "'rex_package_map' can only be used when 'proguard_specs' is also set");
    }

    // TODO(bazel-team): Find a way to simplify this code.
    // treeKeys() means that the resulting map sorts the entries by key, which is necessary to
    // ensure determinism.
    Multimap<String, TransitiveInfoCollection> depsByArchitecture = MultimapBuilder.treeKeys().arrayListValues()
            .build();
    AndroidConfiguration androidConfig = ruleContext.getFragment(AndroidConfiguration.class);
    for (Map.Entry<Optional<String>, ? extends List<? extends TransitiveInfoCollection>> entry : ruleContext
            .getSplitPrerequisites("deps").entrySet()) {
        String cpu = entry.getKey().or(androidConfig.getCpu());
        depsByArchitecture.putAll(cpu, entry.getValue());
    }
    Map<String, BuildConfiguration> configurationMap = new LinkedHashMap<>();
    Map<String, CcToolchainProvider> toolchainMap = new LinkedHashMap<>();
    for (Map.Entry<Optional<String>, ? extends List<? extends TransitiveInfoCollection>> entry : ruleContext
            .getSplitPrerequisites(":cc_toolchain_split").entrySet()) {
        String cpu = entry.getKey().or(androidConfig.getCpu());
        TransitiveInfoCollection dep = Iterables.getOnlyElement(entry.getValue());
        CcToolchainProvider toolchain = CppHelper.getToolchain(ruleContext, dep);
        configurationMap.put(cpu, dep.getConfiguration());
        toolchainMap.put(cpu, toolchain);
    }

    NativeLibs nativeLibs = NativeLibs.fromLinkedNativeDeps(ruleContext,
            androidSemantics.getNativeDepsFileName(), depsByArchitecture, toolchainMap, configurationMap);

    // TODO(bazel-team): Resolve all the different cases of resource handling so this conditional
    // can go away: recompile from android_resources, and recompile from android_binary attributes.
    ApplicationManifest applicationManifest;
    ResourceApk resourceApk;
    ResourceApk incrementalResourceApk;
    ResourceApk instantRunResourceApk;
    ResourceApk splitResourceApk;
    if (LocalResourceContainer.definesAndroidResources(ruleContext.attributes())) {
        // Retrieve and compile the resources defined on the android_binary rule.
        LocalResourceContainer.validateRuleContext(ruleContext);
        ApplicationManifest ruleManifest = androidSemantics.getManifestForRule(ruleContext);

        applicationManifest = ruleManifest.mergeWith(ruleContext, resourceDeps);

        resourceApk = applicationManifest.packWithDataAndResources(
                ruleContext.getImplicitOutputArtifact(AndroidRuleClasses.ANDROID_RESOURCES_APK), ruleContext,
                false, /* isLibrary */
                resourceDeps, ruleContext.getImplicitOutputArtifact(AndroidRuleClasses.ANDROID_R_TXT),
                null, /* Artifact symbolsTxt */
                ruleContext.getTokenizedStringListAttr("resource_configuration_filters"),
                ruleContext.getTokenizedStringListAttr("nocompress_extensions"),
                ruleContext.attributes().get("crunch_png", Type.BOOLEAN),
                ruleContext.getTokenizedStringListAttr("densities"), false, /* incremental */
                ProguardHelper.getProguardConfigArtifact(ruleContext, ""),
                createMainDexProguardSpec(ruleContext),
                ruleContext.getImplicitOutputArtifact(AndroidRuleClasses.ANDROID_PROCESSED_MANIFEST),
                ruleContext.getImplicitOutputArtifact(AndroidRuleClasses.ANDROID_RESOURCES_ZIP),
                DataBinding.isEnabled(ruleContext) ? DataBinding.getLayoutInfoFile(ruleContext) : null);
        ruleContext.assertNoErrors();

        incrementalResourceApk = applicationManifest.addMobileInstallStubApplication(ruleContext)
                .packWithDataAndResources(
                        ruleContext.getImplicitOutputArtifact(
                                AndroidRuleClasses.ANDROID_INCREMENTAL_RESOURCES_APK),
                        ruleContext, false, /* isLibrary */
                        resourceDeps, null, /* Artifact rTxt */
                        null, /* Artifact symbolsTxt */
                        ruleContext.getTokenizedStringListAttr("resource_configuration_filters"),
                        ruleContext.getTokenizedStringListAttr("nocompress_extensions"),
                        ruleContext.attributes().get("crunch_png", Type.BOOLEAN),
                        ruleContext.getTokenizedStringListAttr("densities"), true, /* incremental */
                        ProguardHelper.getProguardConfigArtifact(ruleContext, "incremental"),
                        null, /* mainDexProguardCfg */
                        null, /* manifestOut */
                        null, /* mergedResourcesOut */
                        null /* dataBindingInfoZip */);
        ruleContext.assertNoErrors();

        instantRunResourceApk = applicationManifest.addInstantRunStubApplication(ruleContext)
                .packWithDataAndResources(getDxArtifact(ruleContext, "android_instant_run.ap_"), ruleContext,
                        false, /* isLibrary */
                        resourceDeps, null, /* Artifact rTxt */
                        null, /* Artifact symbolsTxt */
                        ruleContext.getTokenizedStringListAttr("resource_configuration_filters"),
                        ruleContext.getTokenizedStringListAttr("nocompress_extensions"),
                        ruleContext.attributes().get("crunch_png", Type.BOOLEAN),
                        ruleContext.getTokenizedStringListAttr("densities"), true, /* incremental */
                        ProguardHelper.getProguardConfigArtifact(ruleContext, "instant_run"),
                        null, /* mainDexProguardCfg */
                        null, /* manifestOut */
                        null /* mergedResourcesOut */, null /* dataBindingInfoZip */);
        ruleContext.assertNoErrors();

        splitResourceApk = applicationManifest.createSplitManifest(ruleContext, "android_resources", false)
                .packWithDataAndResources(getDxArtifact(ruleContext, "android_resources.ap_"), ruleContext,
                        false, /* isLibrary */
                        resourceDeps, null, /* Artifact rTxt */
                        null, /* Artifact symbolsTxt */
                        ruleContext.getTokenizedStringListAttr("resource_configuration_filters"),
                        ruleContext.getTokenizedStringListAttr("nocompress_extensions"),
                        ruleContext.attributes().get("crunch_png", Type.BOOLEAN),
                        ruleContext.getTokenizedStringListAttr("densities"), true, /* incremental */
                        ProguardHelper.getProguardConfigArtifact(ruleContext, "incremental_split"),
                        null, /* mainDexProguardCfg */
                        null, /* manifestOut */
                        null /* mergedResourcesOut */, null /* dataBindingInfoZip */);
        ruleContext.assertNoErrors();

    } else {

        if (!ruleContext.attributes().get("crunch_png", Type.BOOLEAN)) {
            ruleContext.throwWithRuleError("Setting crunch_png = 0 is not supported for android_binary"
                    + " rules which depend on android_resources rules.");
        }

        // Retrieve the resources from the resources attribute on the android_binary rule
        // and recompile them if necessary.
        ApplicationManifest resourcesManifest = ApplicationManifest.fromResourcesRule(ruleContext);
        if (resourcesManifest == null) {
            throw new RuleErrorException();
        }
        applicationManifest = resourcesManifest.mergeWith(ruleContext, resourceDeps);

        // Always recompiling resources causes AndroidTest to fail in certain circumstances.
        if (shouldRegenerate(ruleContext, resourceDeps)) {
            resourceApk = applicationManifest.packWithResources(
                    ruleContext.getImplicitOutputArtifact(AndroidRuleClasses.ANDROID_RESOURCES_APK),
                    ruleContext, resourceDeps, true, /* createSource */
                    ProguardHelper.getProguardConfigArtifact(ruleContext, ""),
                    createMainDexProguardSpec(ruleContext));
            ruleContext.assertNoErrors();
        } else {
            resourceApk = applicationManifest.useCurrentResources(ruleContext,
                    ProguardHelper.getProguardConfigArtifact(ruleContext, ""),
                    createMainDexProguardSpec(ruleContext));
            ruleContext.assertNoErrors();
        }

        incrementalResourceApk = applicationManifest.addMobileInstallStubApplication(ruleContext)
                .packWithResources(
                        ruleContext.getImplicitOutputArtifact(
                                AndroidRuleClasses.ANDROID_INCREMENTAL_RESOURCES_APK),
                        ruleContext, resourceDeps, false, /* createSource */
                        ProguardHelper.getProguardConfigArtifact(ruleContext, "incremental"),
                        null /* mainDexProguardConfig */);
        ruleContext.assertNoErrors();

        instantRunResourceApk = applicationManifest.addInstantRunStubApplication(ruleContext).packWithResources(
                getDxArtifact(ruleContext, "android_instant_run.ap_"), ruleContext, resourceDeps,
                false, /* createSource */
                ProguardHelper.getProguardConfigArtifact(ruleContext, "instant_run"),
                null /* mainDexProguardConfig */);
        ruleContext.assertNoErrors();

        splitResourceApk = applicationManifest.createSplitManifest(ruleContext, "android_resources", false)
                .packWithResources(getDxArtifact(ruleContext, "android_resources.ap_"), ruleContext,
                        resourceDeps, false, /* createSource */
                        ProguardHelper.getProguardConfigArtifact(ruleContext, "incremental_split"),
                        null /* mainDexProguardConfig */);
        ruleContext.assertNoErrors();
    }

    boolean shrinkResources = shouldShrinkResources(ruleContext);

    JavaTargetAttributes resourceClasses = androidCommon.init(javaSemantics, androidSemantics, resourceApk,
            ruleContext.getConfiguration().isCodeCoverageEnabled(), true /* collectJavaCompilationArgs */,
            true /* isBinary */);
    ruleContext.assertNoErrors();

    Function<Artifact, Artifact> derivedJarFunction = collectDesugaredJars(ruleContext, androidCommon,
            androidSemantics, resourceClasses);
    Artifact deployJar = createDeployJar(ruleContext, javaSemantics, androidCommon, resourceClasses,
            derivedJarFunction);

    Artifact proguardMapping = ruleContext.getPrerequisiteArtifact("proguard_apply_mapping", Mode.TARGET);

    return createAndroidBinary(ruleContext, filesBuilder, deployJar, derivedJarFunction,
            /* isBinaryJarFiltered */ false, javaCommon, androidCommon, javaSemantics, androidSemantics,
            nativeLibs, applicationManifest, resourceApk, incrementalResourceApk, instantRunResourceApk,
            splitResourceApk, shrinkResources, resourceClasses, ImmutableList.<Artifact>of(),
            ImmutableList.<Artifact>of(), proguardMapping);
}

From source file:com.github.jsdossier.TypeInspector.java

/**
 * Extracts information on the members (both functions and properties) of the given type.
 *
 * <p>The returned report will include information on all properties on the type, regardless of
 * whether the property is defined directly on the nominal type or one of its super
 * types/interfaces./*w  w  w.  j av  a 2 s  . c  o m*/
 */
public Report inspectInstanceType() {
    if (!inspectedType.getType().isConstructor() && !inspectedType.getType().isInterface()) {
        return new Report();
    }

    Report report = new Report();
    Multimap<String, InstanceProperty> properties = MultimapBuilder.treeKeys().linkedHashSetValues().build();

    for (JSType assignableType : getAssignableTypes(inspectedType.getType())) {
        for (Map.Entry<String, InstanceProperty> entry : getInstanceProperties(assignableType).entrySet()) {
            properties.put(entry.getKey(), entry.getValue());
        }
    }

    final JSType currentType = ((FunctionType) inspectedType.getType()).getInstanceType();

    for (String key : properties.keySet()) {
        Deque<InstanceProperty> definitions = new ArrayDeque<>(properties.get(key));
        JSType propertyType = findPropertyType(definitions);
        InstanceProperty property = definitions.removeFirst();

        if (property.getJsDoc() != null
                && property.getJsDoc().getVisibility() == JSDocInfo.Visibility.PRIVATE) {
            continue;
        }

        NominalType ownerType = property.getOwnerType().or(inspectedType);
        Comment definedBy = getDefinedByComment(linkFactory, ownerType, currentType, property);

        if (propertyType.isFunctionType()) {
            report.addFunction(getFunctionData(property.getName(), propertyType, property.getNode(),
                    PropertyDocs.create(ownerType, property.getJsDoc()), definedBy, definitions));
        } else {
            report.addProperty(getPropertyData(property.getName(), propertyType, property.getNode(),
                    PropertyDocs.create(ownerType, property.getJsDoc()), definedBy, definitions));
        }
    }

    return report;
}

From source file:com.facebook.buck.android.apkmodule.APKModuleGraph.java

/**
 * For each seed target, find its reachable targets and mark them in a multimap as being reachable
 * by that module for later sorting into exclusive and shared targets
 *
 * @return the Multimap containing targets and the seed modules that contain them
 */// w w w  .j a  v  a 2 s. c  om
private Multimap<BuildTarget, String> mapTargetsToContainingModules() {
    Multimap<BuildTarget, String> targetToContainingApkModuleNameMap = MultimapBuilder.treeKeys()
            .treeSetValues().build();
    for (Map.Entry<String, List<BuildTarget>> seedConfig : getSeedConfigMap().get().entrySet()) {
        String seedModuleName = seedConfig.getKey();
        for (BuildTarget seedTarget : seedConfig.getValue()) {
            targetToContainingApkModuleNameMap.put(seedTarget, seedModuleName);
            new AbstractBreadthFirstTraversal<TargetNode<?>>(targetGraph.get(seedTarget)) {
                @Override
                public ImmutableSet<TargetNode<?>> visit(TargetNode<?> node) {

                    ImmutableSet.Builder<TargetNode<?>> depsBuilder = ImmutableSet.builder();
                    for (BuildTarget depTarget : node.getBuildDeps()) {
                        if (!isInRootModule(depTarget) && !isSeedTarget(depTarget)) {
                            depsBuilder.add(targetGraph.get(depTarget));
                            targetToContainingApkModuleNameMap.put(depTarget, seedModuleName);
                        }
                    }
                    return depsBuilder.build();
                }
            }.start();
        }
    }
    // Now to generate the minimal covers of APKModules for each set of APKModules that contain
    // a buildTarget
    DirectedAcyclicGraph<String> declaredDependencies = getDeclaredDependencyGraph();
    Multimap<BuildTarget, String> targetModuleEntriesToRemove = MultimapBuilder.treeKeys().treeSetValues()
            .build();
    for (BuildTarget key : targetToContainingApkModuleNameMap.keySet()) {
        Collection<String> modulesForTarget = targetToContainingApkModuleNameMap.get(key);
        new AbstractBreadthFirstTraversal<String>(modulesForTarget) {
            @Override
            public Iterable<String> visit(String moduleName) throws RuntimeException {
                Collection<String> dependentModules = declaredDependencies.getIncomingNodesFor(moduleName);
                for (String dependent : dependentModules) {
                    if (modulesForTarget.contains(dependent)) {
                        targetModuleEntriesToRemove.put(key, dependent);
                    }
                }
                return dependentModules;
            }
        }.start();
    }
    for (Map.Entry<BuildTarget, String> entryToRemove : targetModuleEntriesToRemove.entries()) {
        targetToContainingApkModuleNameMap.remove(entryToRemove.getKey(), entryToRemove.getValue());
    }
    return targetToContainingApkModuleNameMap;
}

From source file:com.github.jsdossier.DocWriter.java

private void getPrototypeData(JsType.Builder jsTypeBuilder, IndexReference indexReference) {
    NominalType nominalType = indexReference.getNominalType();
    Iterable<JSType> assignableTypes;
    if (nominalType.getJsType().isConstructor()) {
        assignableTypes = Iterables.concat(
                Lists.reverse(typeRegistry.getTypeHierarchy(nominalType.getJsType())),
                typeRegistry.getImplementedTypes(nominalType));

    } else if (nominalType.getJsType().isInterface()) {
        assignableTypes = Iterables.concat(ImmutableSet.of(nominalType.getJsType()),
                typeRegistry.getImplementedTypes(nominalType));
    } else {//from w  w w.j a va  2s .c o m
        return;
    }

    Multimap<String, InstanceProperty> properties = MultimapBuilder.treeKeys().linkedHashSetValues().build();

    for (JSType assignableType : assignableTypes) {
        if (assignableType.isConstructor() || assignableType.isInterface()) {
            assignableType = ((FunctionType) assignableType).getInstanceType();
        }

        ObjectType object = assignableType.toObjectType();
        FunctionType ctor = object.getConstructor();
        Set<String> ownProps = new HashSet<>();

        for (String pname : object.getOwnPropertyNames()) {
            if (!"constructor".equals(pname)) {
                ownProps.add(pname);
                Property property = object.getOwnSlot(pname);
                properties.put(pname, new InstanceProperty(object, property.getName(),
                        getType(object, property), property.getNode(), property.getJSDocInfo()));
            }
        }

        if (ctor == null) {
            continue;
        }

        ObjectType prototype = ObjectType.cast(ctor.getPropertyType("prototype"));
        verify(prototype != null);

        for (String pname : prototype.getOwnPropertyNames()) {
            if (!"constructor".equals(pname) && !ownProps.contains(pname)) {
                Property property = prototype.getOwnSlot(pname);
                properties.put(pname, new InstanceProperty(object, property.getName(),
                        getType(object, property), property.getNode(), property.getJSDocInfo()));
            }
        }
    }

    if (properties.isEmpty()) {
        return;
    }

    JSType docType = nominalType.getJsType();
    if (docType.isConstructor() || docType.isInterface()) {
        docType = ((FunctionType) docType).getInstanceType();
    }

    for (String key : properties.keySet()) {
        LinkedList<InstanceProperty> definitions = new LinkedList<>(properties.get(key));
        InstanceProperty property = definitions.removeFirst();

        Comment definedBy = null;
        if (!docType.equals(property.getDefinedOn())) {
            JSType definedByType = stripTemplateTypeInformation(property.getDefinedOn());
            definedBy = linker.formatTypeExpression(definedByType);
        }
        Comment overrides = findOverriddenType(definitions);
        Iterable<Comment> specifications = findSpecifications(definitions);

        JsDoc jsdoc = JsDoc.from(property.getJSDocInfo());
        if (jsdoc != null && jsdoc.getVisibility() == JSDocInfo.Visibility.PRIVATE) {
            continue;
        }

        // TODO: include inherited properties in UI without generate lots of redundant info.
        if (definedBy != null) {
            continue;
        }

        JSType propType = property.getType();
        BaseProperty base;
        if (propType.isFunctionType()) {
            com.github.jsdossier.proto.Function data = getFunctionData(property.getName(), propType,
                    property.getNode(), jsdoc, definedBy, overrides, specifications);
            jsTypeBuilder.addMethod(data);
            base = data.getBase();
        } else {
            com.github.jsdossier.proto.Property data = getPropertyData(property.getName(), propType,
                    property.getNode(), jsdoc, definedBy, overrides, specifications);
            jsTypeBuilder.addField(data);
            base = data.getBase();
        }

        // Do not include the property in the search index if the parent type is an alias,
        // the property is inherited from another type, or the property overrides a parent
        // property but does not provide a comment of its own.
        if (!jsTypeBuilder.hasAliasedType() && !base.hasDefinedBy() && (!base.hasOverrides()
                || (base.hasDescription() && base.getDescription().getTokenCount() > 0))) {
            indexReference.addInstanceProperty(base.getName());
        }
    }
}