List of usage examples for com.google.common.collect ImmutableMap values
public ImmutableCollection<V> values()
From source file:google.registry.model.registry.label.PremiumListUtils.java
/** * Persists a new or updated PremiumList object and its descendant entities to Datastore. * * <p>The flow here is: save the new premium list entries parented on that revision entity, * save/update the PremiumList, and then delete the old premium list entries associated with the * old revision./*from ww w . ja v a 2 s . co m*/ * * <p>This is the only valid way to save these kinds of entities! */ public static PremiumList savePremiumListAndEntries(final PremiumList premiumList, ImmutableMap<String, PremiumListEntry> premiumListEntries) { final Optional<PremiumList> oldPremiumList = PremiumList.get(premiumList.getName()); // Create the new revision (with its bloom filter) and parent the entries on it. final PremiumListRevision newRevision = PremiumListRevision.create(premiumList, premiumListEntries.keySet()); final Key<PremiumListRevision> newRevisionKey = Key.create(newRevision); ImmutableSet<PremiumListEntry> parentedEntries = parentPremiumListEntriesOnRevision( premiumListEntries.values(), newRevisionKey); // Save the new child entities in a series of transactions. for (final List<PremiumListEntry> batch : partition(parentedEntries, TRANSACTION_BATCH_SIZE)) { ofy().transactNew(new VoidWork() { @Override public void vrun() { ofy().save().entities(batch); } }); } // Save the new PremiumList and revision itself. PremiumList updated = ofy().transactNew(new Work<PremiumList>() { @Override public PremiumList run() { DateTime now = ofy().getTransactionTime(); // Assert that the premium list hasn't been changed since we started this process. PremiumList existing = ofy().load().type(PremiumList.class).parent(getCrossTldKey()) .id(premiumList.getName()).now(); checkState(Objects.equals(existing, oldPremiumList.orNull()), "PremiumList was concurrently edited"); PremiumList newList = premiumList.asBuilder().setLastUpdateTime(now) .setCreationTime(oldPremiumList.isPresent() ? oldPremiumList.get().creationTime : now) .setRevision(newRevisionKey).build(); ofy().save().entities(newList, newRevision); return newList; } }); // Update the cache. cachePremiumLists.put(premiumList.getName(), updated); // Delete the entities under the old PremiumList. if (oldPremiumList.isPresent()) { deleteRevisionAndEntriesOfPremiumList(oldPremiumList.get()); } return updated; }
From source file:com.facebook.buck.cxx.Omnibus.java
protected static OmnibusLibrary createOmnibus(BuildRuleParams params, BuildRuleResolver ruleResolver, SourcePathResolver pathResolver, SourcePathRuleFinder ruleFinder, CxxBuckConfig cxxBuckConfig, CxxPlatform cxxPlatform, ImmutableList<? extends Arg> extraLdflags, OmnibusSpec spec) throws NoSuchBuildTargetException { ImmutableList.Builder<Arg> argsBuilder = ImmutableList.builder(); // Add extra ldflags to the beginning of the link. argsBuilder.addAll(extraLdflags);/*from w w w .j a v a 2 s . com*/ // For roots that aren't dependencies of nodes in the body, we extract their undefined symbols // to add to the link so that required symbols get pulled into the merged library. List<SourcePath> undefinedSymbolsOnlyRoots = new ArrayList<>(); for (BuildTarget target : Sets.difference(spec.getRoots().keySet(), spec.getGraph().getNodes())) { NativeLinkTarget linkTarget = Preconditions.checkNotNull(spec.getRoots().get(target)); undefinedSymbolsOnlyRoots.add(new BuildTargetSourcePath(getRootTarget(params.getBuildTarget(), shouldCreateDummyRoot(linkTarget, cxxPlatform) ? getDummyRootTarget(target) : target))); } argsBuilder.addAll(createUndefinedSymbolsArgs(params, ruleResolver, pathResolver, ruleFinder, cxxPlatform, undefinedSymbolsOnlyRoots)); // Walk the graph in topological order, appending each nodes contributions to the link. ImmutableList<BuildTarget> targets = TopologicalSort.sort(spec.getGraph()).reverse(); for (BuildTarget target : targets) { // If this is a root, just place the shared library we've linked above onto the link line. // We need this so that the linker can grab any undefined symbols from it, and therefore // know which symbols to pull in from the body nodes. NativeLinkTarget root = spec.getRoots().get(target); if (root != null) { argsBuilder.add(new SourcePathArg(pathResolver, new BuildTargetSourcePath(getRootTarget(params.getBuildTarget(), root.getBuildTarget())))); continue; } // Otherwise, this is a body node, and we need to add its static library to the link line, // so that the linker can discard unused object files from it. NativeLinkable nativeLinkable = Preconditions.checkNotNull(spec.getBody().get(target)); NativeLinkableInput input = NativeLinkables.getNativeLinkableInput(cxxPlatform, Linker.LinkableDepType.STATIC_PIC, nativeLinkable); argsBuilder.addAll(input.getArgs()); } // We process all excluded omnibus deps last, and just add their components as if this were a // normal shared link. ImmutableMap<BuildTarget, NativeLinkable> deps = NativeLinkables.getNativeLinkables(cxxPlatform, spec.getDeps().values(), Linker.LinkableDepType.SHARED); for (NativeLinkable nativeLinkable : deps.values()) { NativeLinkableInput input = NativeLinkables.getNativeLinkableInput(cxxPlatform, Linker.LinkableDepType.SHARED, nativeLinkable); argsBuilder.addAll(input.getArgs()); } // Create the merged omnibus library using the arguments assembled above. BuildTarget omnibusTarget = params.getBuildTarget().withAppendedFlavors(OMNIBUS_FLAVOR); String omnibusSoname = getOmnibusSoname(cxxPlatform); ruleResolver.addToIndex(CxxLinkableEnhancer.createCxxLinkableSharedBuildRule(cxxBuckConfig, cxxPlatform, params, ruleResolver, pathResolver, ruleFinder, omnibusTarget, BuildTargets.getGenPath(params.getProjectFilesystem(), omnibusTarget, "%s").resolve(omnibusSoname), Optional.of(omnibusSoname), argsBuilder.build())); return OmnibusLibrary.of(omnibusSoname, new BuildTargetSourcePath(omnibusTarget)); }
From source file:com.google.idea.blaze.cpp.BlazeConfigurationResolver.java
private static Set<ExecutionRootPath> collectExecutionRootPaths(TargetMap targetMap, ImmutableMap<TargetKey, CToolchainIdeInfo> toolchainLookupMap) { Set<ExecutionRootPath> paths = Sets.newHashSet(); for (TargetIdeInfo target : targetMap.targets()) { if (target.cIdeInfo != null) { paths.addAll(target.cIdeInfo.transitiveSystemIncludeDirectories); paths.addAll(target.cIdeInfo.transitiveIncludeDirectories); paths.addAll(target.cIdeInfo.transitiveQuoteIncludeDirectories); }/*w ww.ja v a2 s . c o m*/ } for (CToolchainIdeInfo toolchain : toolchainLookupMap.values()) { paths.addAll(toolchain.builtInIncludeDirectories); paths.addAll(toolchain.unfilteredToolchainSystemIncludes); } return paths; }
From source file:com.facebook.buck.core.cell.impl.LocalCellProviderFactory.java
/** Create a cell provider at a given root. */ public static CellProvider create(ProjectFilesystem rootFilesystem, BuckConfig rootConfig, CellConfig rootCellConfigOverrides, ImmutableMap<CellName, Path> cellPathMapping, CellPathResolver rootCellCellPathResolver, BuckModuleManager moduleManager, ToolchainProviderFactory toolchainProviderFactory, ProjectFilesystemFactory projectFilesystemFactory, UnconfiguredBuildTargetFactory unconfiguredBuildTargetFactory) { ImmutableMap<Path, RawConfig> pathToConfigOverrides; try {// w w w.j a va 2 s . com pathToConfigOverrides = rootCellConfigOverrides.getOverridesByPath(cellPathMapping); } catch (InvalidCellOverrideException e) { throw new HumanReadableException(e.getMessage()); } ImmutableSet<Path> allRoots = ImmutableSet.copyOf(cellPathMapping.values()); return new CellProvider(cellProvider -> new CacheLoader<Path, Cell>() { @Override public Cell load(Path cellPath) throws IOException, InterruptedException { Path normalizedCellPath = cellPath.toRealPath().normalize(); Preconditions.checkState(allRoots.contains(normalizedCellPath), "Cell %s outside of transitive closure of root cell (%s).", normalizedCellPath, allRoots); RawConfig configOverrides = Optional.ofNullable(pathToConfigOverrides.get(normalizedCellPath)) .orElse(RawConfig.of(ImmutableMap.of())); Config config = Configs.createDefaultConfig(normalizedCellPath, configOverrides); ImmutableMap<String, Path> cellMapping = DefaultCellPathResolver .getCellPathsFromConfigRepositoriesSection(cellPath, config.get(DefaultCellPathResolver.REPOSITORIES_SECTION)); // The cell should only contain a subset of cell mappings of the root cell. cellMapping.forEach((name, path) -> { Path pathInRootResolver = rootCellCellPathResolver.getCellPaths().get(name); if (pathInRootResolver == null) { throw new HumanReadableException( "In the config of %s: %s.%s must exist in the root cell's cell mappings.", cellPath.toString(), DefaultCellPathResolver.REPOSITORIES_SECTION, name); } else if (!pathInRootResolver.equals(path)) { throw new HumanReadableException( "In the config of %s: %s.%s must point to the same directory as the root " + "cell's cell mapping: (root) %s != (current) %s", cellPath.toString(), DefaultCellPathResolver.REPOSITORIES_SECTION, name, pathInRootResolver, path); } }); CellPathResolver cellPathResolver = new CellPathResolverView(rootCellCellPathResolver, cellMapping.keySet(), cellPath); Optional<EmbeddedCellBuckOutInfo> embeddedCellBuckOutInfo = Optional.empty(); Optional<String> canonicalCellName = cellPathResolver.getCanonicalCellName(normalizedCellPath); if (rootConfig.getView(BuildBuckConfig.class).isEmbeddedCellBuckOutEnabled() && canonicalCellName.isPresent()) { embeddedCellBuckOutInfo = Optional .of(EmbeddedCellBuckOutInfo.of(rootFilesystem.resolve(rootFilesystem.getRootPath()), rootFilesystem.getBuckPaths(), canonicalCellName.get())); } ProjectFilesystem cellFilesystem = projectFilesystemFactory .createProjectFilesystem(normalizedCellPath, config, embeddedCellBuckOutInfo); BuckConfig buckConfig = new BuckConfig(config, cellFilesystem, rootConfig.getArchitecture(), rootConfig.getPlatform(), rootConfig.getEnvironment(), buildTargetName -> unconfiguredBuildTargetFactory.create(cellPathResolver, buildTargetName)); RuleKeyConfiguration ruleKeyConfiguration = ConfigRuleKeyConfigurationFactory.create(buckConfig, moduleManager); ToolchainProvider toolchainProvider = toolchainProviderFactory.create(buckConfig, cellFilesystem, ruleKeyConfiguration); // TODO(13777679): cells in other watchman roots do not work correctly. return ImmutableCell.of(cellPathResolver.getKnownRoots(), canonicalCellName, cellFilesystem, buckConfig, cellProvider, toolchainProvider, ruleKeyConfiguration, cellPathResolver); } }, cellProvider -> RootCellFactory.create(cellProvider, rootCellCellPathResolver, toolchainProviderFactory, rootFilesystem, moduleManager, rootConfig)); }
From source file:com.facebook.buck.cxx.CxxLibraryFactory.java
private static ImmutableList<SourcePath> requireObjects(BuildTarget buildTarget, ProjectFilesystem projectFilesystem, ActionGraphBuilder graphBuilder, SourcePathResolver sourcePathResolver, SourcePathRuleFinder ruleFinder, CellPathResolver cellRoots, CxxBuckConfig cxxBuckConfig, CxxPlatform cxxPlatform, PicType pic, CxxLibraryDescriptionArg args, ImmutableSet<BuildRule> deps, CxxLibraryDescription.TransitiveCxxPreprocessorInputFunction transitivePreprocessorInputs, Optional<CxxLibraryDescriptionDelegate> delegate) { // TODO(T21900747): Fix dependence on order of object paths ImmutableList.Builder<SourcePath> builder = ImmutableList.builder(); ImmutableMap<CxxPreprocessAndCompile, SourcePath> cxxObjects = requireCxxObjects(buildTarget, projectFilesystem, graphBuilder, sourcePathResolver, ruleFinder, cellRoots, cxxBuckConfig, cxxPlatform, pic, args, deps, transitivePreprocessorInputs, delegate); builder.addAll(cxxObjects.values()); Optional<ImmutableList<SourcePath>> pluginObjectPaths = delegate .flatMap(p -> p.getObjectFilePaths(buildTarget, graphBuilder, cxxPlatform)); pluginObjectPaths.ifPresent(paths -> builder.addAll(paths)); return builder.build(); }
From source file:com.facebook.buck.features.haskell.HaskellGhciDescription.java
/** * @param omnibusRoots roots of the graph of nodes (including transitive deps) to include in the * omnibus link.//from w w w . j ava2s .co m * @param excludedRoots roots of a the graph of nodes (including transitive deps) that cannot be * included in the omnibus link. * @return the {@link HaskellGhciOmnibusSpec} describing the omnibus link. */ public static HaskellGhciOmnibusSpec getOmnibusSpec(BuildTarget baseTarget, CxxPlatform cxxPlatform, ActionGraphBuilder graphBuilder, ImmutableMap<BuildTarget, ? extends NativeLinkable> omnibusRoots, ImmutableMap<BuildTarget, ? extends NativeLinkable> excludedRoots) { LOG.verbose("%s: omnibus roots: %s", baseTarget, omnibusRoots); LOG.verbose("%s: excluded roots: %s", baseTarget, excludedRoots); HaskellGhciOmnibusSpec.Builder builder = HaskellGhciOmnibusSpec.builder(); // Calculate excluded roots/deps, and add them to the link. ImmutableMap<BuildTarget, NativeLinkable> transitiveExcludedLinkables = NativeLinkables .getTransitiveNativeLinkables(cxxPlatform, graphBuilder, excludedRoots.values()); builder.setExcludedRoots(excludedRoots); builder.setExcludedTransitiveDeps(transitiveExcludedLinkables); // Calculate the body and first-order deps of omnibus. new AbstractBreadthFirstTraversal<NativeLinkable>(omnibusRoots.values()) { @Override public Iterable<? extends NativeLinkable> visit(NativeLinkable nativeLinkable) { // Excluded linkables can't be included in omnibus. if (transitiveExcludedLinkables.containsKey(nativeLinkable.getBuildTarget())) { LOG.verbose("%s: skipping excluded linkable %s", baseTarget, nativeLinkable.getBuildTarget()); return ImmutableSet.of(); } // We cannot include prebuilt SOs in omnibus. // // TODO(agallagher): We should also use `NativeLinkable.supportsOmnibusLinking()` to // determine if we can include the library, but this will need likely need to be updated for // a multi-pass walk first. if (isPrebuiltSO(nativeLinkable, cxxPlatform, graphBuilder)) { builder.putDeps(nativeLinkable.getBuildTarget(), nativeLinkable); LOG.verbose("%s: skipping prebuilt SO %s", baseTarget, nativeLinkable.getBuildTarget()); return ImmutableSet.of(); } // Include C/C++ libs capable of static linking in omnibus. // // TODO(agallagher): This should probably be *any* `NativeLinkable` that supports omnibus // linking. if (nativeLinkable instanceof CxxLibrary || nativeLinkable instanceof PrebuiltCxxLibrary) { builder.putBody(nativeLinkable.getBuildTarget(), nativeLinkable); LOG.verbose("%s: including C/C++ library %s", baseTarget, nativeLinkable.getBuildTarget()); return Iterables.concat( nativeLinkable.getNativeLinkableDepsForPlatform(cxxPlatform, graphBuilder), nativeLinkable.getNativeLinkableExportedDepsForPlatform(cxxPlatform, graphBuilder)); } // Unexpected node. Can this actually happen? // // TODO(agallagher): This should probably be an internal error/assertion, as silently // dropping libraries at this point will likely result in we're user errors. return ImmutableSet.of(); } }.start(); HaskellGhciOmnibusSpec spec = builder.build(); LOG.verbose("%s: built omnibus spec %s", spec); return spec; }
From source file:com.facebook.buck.java.intellij.IjModuleGraph.java
/** * @param targetGraph input graph.// ww w . j av a2 s . co m * @param libraryFactory library factory. * @param moduleFactory module factory. * @param aggregationMode module aggregation mode. * @return module graph corresponding to the supplied {@link TargetGraph}. Multiple targets from * the same base path are mapped to a single module, therefore an IjModuleGraph edge * exists between two modules (Ma, Mb) if a TargetGraph edge existed between a pair of * nodes (Ta, Tb) and Ma contains Ta and Mb contains Tb. */ public static IjModuleGraph from(final TargetGraph targetGraph, final IjLibraryFactory libraryFactory, final IjModuleFactory moduleFactory, AggregationMode aggregationMode) { final ImmutableMap<BuildTarget, IjModule> rulesToModules = createModules(targetGraph, moduleFactory, aggregationMode.getBasePathTransform(targetGraph.getNodes().size())); final ExportedDepsClosureResolver exportedDepsClosureResolver = new ExportedDepsClosureResolver( targetGraph); ImmutableMap.Builder<IjProjectElement, ImmutableMap<IjProjectElement, DependencyType>> depsBuilder = ImmutableMap .builder(); final Set<IjLibrary> referencedLibraries = new HashSet<>(); for (final IjModule module : FluentIterable.from(rulesToModules.values()).toSet()) { Map<IjProjectElement, DependencyType> moduleDeps = new HashMap<>(); for (Map.Entry<BuildTarget, DependencyType> entry : module.getDependencies().entrySet()) { BuildTarget depBuildTarget = entry.getKey(); DependencyType depType = entry.getValue(); ImmutableSet<IjProjectElement> depElements; if (depType.equals(DependencyType.COMPILED_SHADOW)) { TargetNode<?> targetNode = Preconditions.checkNotNull(targetGraph.get(depBuildTarget)); Optional<IjLibrary> library = libraryFactory.getLibrary(targetNode); if (library.isPresent()) { depElements = ImmutableSet.<IjProjectElement>of(library.get()); } else { depElements = ImmutableSet.of(); } } else { depElements = FluentIterable .from(exportedDepsClosureResolver.getExportedDepsClosure(depBuildTarget)) .append(depBuildTarget).filter(new Predicate<BuildTarget>() { @Override public boolean apply(BuildTarget input) { // The exported deps closure can contain references back to targets contained // in the module, so filter those out. TargetNode<?> targetNode = targetGraph.get(input); return !module.getTargets().contains(targetNode); } }).transform(new Function<BuildTarget, IjProjectElement>() { @Nullable @Override public IjProjectElement apply(BuildTarget depTarget) { IjModule depModule = rulesToModules.get(depTarget); if (depModule != null) { return depModule; } TargetNode<?> targetNode = Preconditions .checkNotNull(targetGraph.get(depTarget)); IjLibrary library = libraryFactory.getLibrary(targetNode).orNull(); return library; } }).filter(Predicates.notNull()).toSet(); } for (IjProjectElement depElement : depElements) { Preconditions.checkState(!depElement.equals(module)); DependencyType.putWithMerge(moduleDeps, depElement, depType); } } if (!module.getExtraClassPathDependencies().isEmpty()) { IjLibrary extraClassPathLibrary = IjLibrary.builder() .setClassPaths(module.getExtraClassPathDependencies()) .setTargets(ImmutableSet.<TargetNode<?>>of()) .setName("library_" + module.getName() + "_extra_classpath").build(); moduleDeps.put(extraClassPathLibrary, DependencyType.PROD); } referencedLibraries.addAll(FluentIterable.from(moduleDeps.keySet()).filter(IjLibrary.class).toSet()); depsBuilder.put(module, ImmutableMap.copyOf(moduleDeps)); } for (IjLibrary library : referencedLibraries) { depsBuilder.put(library, ImmutableMap.<IjProjectElement, DependencyType>of()); } return new IjModuleGraph(depsBuilder.build()); }
From source file:com.facebook.buck.jvm.java.intellij.IjModuleGraph.java
/** * @param projectConfig the project config used * @param targetGraph input graph./* w w w . j a v a 2 s. c o m*/ * @param libraryFactory library factory. * @param moduleFactory module factory. * @param aggregationMode module aggregation mode. * @return module graph corresponding to the supplied {@link TargetGraph}. Multiple targets from * the same base path are mapped to a single module, therefore an IjModuleGraph edge * exists between two modules (Ma, Mb) if a TargetGraph edge existed between a pair of * nodes (Ta, Tb) and Ma contains Ta and Mb contains Tb. */ public static IjModuleGraph from(final IjProjectConfig projectConfig, final TargetGraph targetGraph, final IjLibraryFactory libraryFactory, final IjModuleFactory moduleFactory, AggregationMode aggregationMode) { final ImmutableMap<BuildTarget, IjModule> rulesToModules = createModules(projectConfig, targetGraph, moduleFactory, aggregationMode.getGraphMinimumDepth(targetGraph.getNodes().size())); final ExportedDepsClosureResolver exportedDepsClosureResolver = new ExportedDepsClosureResolver( targetGraph); ImmutableMap.Builder<IjProjectElement, ImmutableMap<IjProjectElement, DependencyType>> depsBuilder = ImmutableMap .builder(); final Set<IjLibrary> referencedLibraries = new HashSet<>(); for (final IjModule module : ImmutableSet.copyOf(rulesToModules.values())) { Map<IjProjectElement, DependencyType> moduleDeps = new HashMap<>(); for (Map.Entry<BuildTarget, DependencyType> entry : module.getDependencies().entrySet()) { BuildTarget depBuildTarget = entry.getKey(); DependencyType depType = entry.getValue(); ImmutableSet<IjProjectElement> depElements; if (depType.equals(DependencyType.COMPILED_SHADOW)) { TargetNode<?, ?> targetNode = targetGraph.get(depBuildTarget); Optional<IjLibrary> library = libraryFactory.getLibrary(targetNode); if (library.isPresent()) { depElements = ImmutableSet.of(library.get()); } else { depElements = ImmutableSet.of(); } } else { depElements = Stream .concat(exportedDepsClosureResolver.getExportedDepsClosure(depBuildTarget).stream(), Stream.of(depBuildTarget)) .filter(input -> { // The exported deps closure can contain references back to targets contained // in the module, so filter those out. TargetNode<?, ?> targetNode = targetGraph.get(input); return !module.getTargets().contains(targetNode); }).map(depTarget -> { IjModule depModule = rulesToModules.get(depTarget); if (depModule != null) { return depModule; } TargetNode<?, ?> targetNode = targetGraph.get(depTarget); return libraryFactory.getLibrary(targetNode).orElse(null); }).filter(Objects::nonNull).collect(MoreCollectors.toImmutableSet()); } for (IjProjectElement depElement : depElements) { Preconditions.checkState(!depElement.equals(module)); DependencyType.putWithMerge(moduleDeps, depElement, depType); } } if (!module.getExtraClassPathDependencies().isEmpty()) { IjLibrary extraClassPathLibrary = IjLibrary.builder() .setClassPaths(module.getExtraClassPathDependencies()).setTargets(ImmutableSet.of()) .setName("library_" + module.getName() + "_extra_classpath").build(); moduleDeps.put(extraClassPathLibrary, DependencyType.PROD); } moduleDeps.keySet().stream().filter(dep -> dep instanceof IjLibrary).map(library -> (IjLibrary) library) .forEach(referencedLibraries::add); depsBuilder.put(module, ImmutableMap.copyOf(moduleDeps)); } referencedLibraries.forEach(library -> depsBuilder.put(library, ImmutableMap.of())); return new IjModuleGraph(depsBuilder.build()); }
From source file:com.facebook.buck.ide.intellij.IjModuleGraphFactory.java
/** * @param projectConfig the project config used * @param targetGraph input graph./*from ww w . j a v a 2s. c om*/ * @param libraryFactory library factory. * @param moduleFactory module factory. * @return module graph corresponding to the supplied {@link TargetGraph}. Multiple targets from * the same base path are mapped to a single module, therefore an IjModuleGraph edge exists * between two modules (Ma, Mb) if a TargetGraph edge existed between a pair of nodes (Ta, Tb) * and Ma contains Ta and Mb contains Tb. */ public static IjModuleGraph from(final ProjectFilesystem projectFilesystem, final IjProjectConfig projectConfig, final TargetGraph targetGraph, final IjLibraryFactory libraryFactory, final IjModuleFactory moduleFactory, final AggregationModuleFactory aggregationModuleFactory) { ImmutableSet<String> ignoredTargetLabels = projectConfig.getIgnoredTargetLabels(); final ImmutableMap<BuildTarget, IjModule> rulesToModules = createModules(projectFilesystem, targetGraph, moduleFactory, aggregationModuleFactory, projectConfig.getAggregationMode().getGraphMinimumDepth(targetGraph.getNodes().size()), ignoredTargetLabels); final ExportedDepsClosureResolver exportedDepsClosureResolver = new ExportedDepsClosureResolver(targetGraph, ignoredTargetLabels); ImmutableMap.Builder<IjProjectElement, ImmutableMap<IjProjectElement, DependencyType>> depsBuilder = ImmutableMap .builder(); final Set<IjLibrary> referencedLibraries = new HashSet<>(); for (final IjModule module : ImmutableSet.copyOf(rulesToModules.values())) { Map<IjProjectElement, DependencyType> moduleDeps = new HashMap<>(); for (Map.Entry<BuildTarget, DependencyType> entry : module.getDependencies().entrySet()) { BuildTarget depBuildTarget = entry.getKey(); TargetNode<?, ?> depTargetNode = targetGraph.get(depBuildTarget); AbstractDescriptionArg arg = (AbstractDescriptionArg) depTargetNode.getConstructorArg(); if (arg.labelsContainsAnyOf(ignoredTargetLabels)) { continue; } DependencyType depType = entry.getValue(); ImmutableSet<IjProjectElement> depElements; if (depType.equals(DependencyType.COMPILED_SHADOW)) { Optional<IjLibrary> library = libraryFactory.getLibrary(depTargetNode); if (library.isPresent()) { depElements = ImmutableSet.of(library.get()); } else { depElements = ImmutableSet.of(); } } else { depElements = Stream .concat(exportedDepsClosureResolver.getExportedDepsClosure(depBuildTarget).stream(), Stream.of(depBuildTarget)) .filter(input -> { TargetNode<?, ?> targetNode = targetGraph.get(input); // IntelliJ doesn't support referring to source files which aren't below the root of // the project. Filter out those cases proactively, so that we don't try to resolve // files relative to the wrong ProjectFilesystem. // Maybe one day someone will fix this. return isInRootCell(projectFilesystem, targetNode); }).filter(input -> { // The exported deps closure can contain references back to targets contained // in the module, so filter those out. return !module.getTargets().contains(input); }).map(depTarget -> { IjModule depModule = rulesToModules.get(depTarget); if (depModule != null) { return depModule; } TargetNode<?, ?> targetNode = targetGraph.get(depTarget); return libraryFactory.getLibrary(targetNode).orElse(null); }).filter(Objects::nonNull).collect(MoreCollectors.toImmutableSet()); } for (IjProjectElement depElement : depElements) { Preconditions.checkState(!depElement.equals(module)); DependencyType.putWithMerge(moduleDeps, depElement, depType); } } if (!module.getExtraClassPathDependencies().isEmpty()) { IjLibrary extraClassPathLibrary = IjLibrary.builder() .setClassPaths(module.getExtraClassPathDependencies()).setTargets(ImmutableSet.of()) .setName("library_" + module.getName() + "_extra_classpath").build(); moduleDeps.put(extraClassPathLibrary, DependencyType.PROD); } moduleDeps.keySet().stream().filter(dep -> dep instanceof IjLibrary).map(library -> (IjLibrary) library) .forEach(referencedLibraries::add); depsBuilder.put(module, ImmutableMap.copyOf(moduleDeps)); } referencedLibraries.forEach(library -> depsBuilder.put(library, ImmutableMap.of())); return new IjModuleGraph(depsBuilder.build()); }
From source file:org.glowroot.agent.weaving.ClassAnalyzer.java
private static List<AnalyzedClass> hack(ThinClass thinClass, ClassLoader loader, List<AnalyzedClass> superAnalyzedClasses, Set<String> ejbRemoteInterfaces) { Map<String, List<String>> superInterfaceNames = Maps.newHashMap(); for (AnalyzedClass analyzedClass : superAnalyzedClasses) { if (analyzedClass.isInterface()) { superInterfaceNames.put(analyzedClass.name(), analyzedClass.interfaceNames()); }//from w w w . java 2 s . c o m } Map<String, String> interfaceNamesToInstrument = Maps.newHashMap(); for (String ejbRemoteInterface : ejbRemoteInterfaces) { addToInterfaceNamesToInstrument(ejbRemoteInterface, superInterfaceNames, interfaceNamesToInstrument, ejbRemoteInterface); } List<InstrumentationConfig> instrumentationConfigs = Lists.newArrayList(); for (Map.Entry<String, String> entry : interfaceNamesToInstrument.entrySet()) { String shortClassName = entry.getValue(); int index = shortClassName.lastIndexOf('.'); if (index != -1) { shortClassName = shortClassName.substring(index + 1); } index = shortClassName.lastIndexOf('$'); if (index != -1) { shortClassName = shortClassName.substring(index + 1); } instrumentationConfigs.add(ImmutableInstrumentationConfig.builder().className(entry.getKey()) .subTypeRestriction(ClassNames.fromInternalName(thinClass.name())).methodName("*") .addMethodParameterTypes("..").captureKind(CaptureKind.TRANSACTION).transactionType("Web") .transactionNameTemplate("EJB remote: " + shortClassName + "#{{methodName}}") .traceEntryMessageTemplate("EJB remote: " + entry.getValue() + ".{{methodName}}()") .timerName("ejb remote").build()); } ImmutableMap<Advice, LazyDefinedClass> newAdvisors = AdviceGenerator.createAdvisors(instrumentationConfigs, null, false, false); try { ClassLoaders.defineClasses(newAdvisors.values(), loader); } catch (Exception e) { logger.error(e.getMessage(), e); } Map<String, Advice> newAdvisorsByRemoteInterface = Maps.newHashMap(); for (Advice advice : newAdvisors.keySet()) { newAdvisorsByRemoteInterface.put(advice.pointcut().className(), advice); } List<AnalyzedClass> ejbHackedSuperAnalyzedClasses = Lists.newArrayList(); for (AnalyzedClass superAnalyzedClass : superAnalyzedClasses) { Advice advice = newAdvisorsByRemoteInterface.get(superAnalyzedClass.name()); if (advice == null) { ejbHackedSuperAnalyzedClasses.add(superAnalyzedClass); } else { ImmutableAnalyzedClass.Builder builder = ImmutableAnalyzedClass.builder() .copyFrom(superAnalyzedClass); List<AnalyzedMethod> analyzedMethods = Lists.newArrayList(); for (AnalyzedMethod analyzedMethod : superAnalyzedClass.analyzedMethods()) { analyzedMethods.add(ImmutableAnalyzedMethod.builder().copyFrom(analyzedMethod) .addSubTypeRestrictedAdvisors(advice).build()); } builder.analyzedMethods(analyzedMethods); ejbHackedSuperAnalyzedClasses.add(builder.build()); } } return ejbHackedSuperAnalyzedClasses; }