List of usage examples for com.google.common.collect ImmutableMap keySet
public ImmutableSet<K> keySet()
From source file:com.google.devtools.build.android.desugar.Desugar.java
/** * Desugar the classes that are generated on the fly when we are desugaring the classes in the * specified inputs.//from w w w . j a v a 2 s . co m */ private void desugarAndWriteDumpedLambdaClassesToOutput(OutputFileProvider outputFileProvider, ClassLoader loader, ClassReaderFactory readerFactory, Builder<String> interfaceLambdaMethodCollector) throws IOException { ImmutableSet<String> interfaceLambdaMethods = interfaceLambdaMethodCollector.build(); checkState(!allowDefaultMethods || interfaceLambdaMethods.isEmpty(), "Desugaring with default methods enabled moved interface lambdas"); // Write out the lambda classes we generated along the way ImmutableMap<Path, LambdaInfo> lambdaClasses = lambdas.drain(); checkState(!options.onlyDesugarJavac9ForLint || lambdaClasses.isEmpty(), "There should be no lambda classes generated: %s", lambdaClasses.keySet()); for (Map.Entry<Path, LambdaInfo> lambdaClass : lambdaClasses.entrySet()) { try (InputStream bytecode = Files.newInputStream(dumpDirectory.resolve(lambdaClass.getKey()))) { ClassReader reader = rewriter.reader(bytecode); UnprefixingClassWriter writer = rewriter.writer(ClassWriter.COMPUTE_MAXS /*for invoking bridges*/); ClassVisitor visitor = createClassVisitorsForDumpedLambdaClasses(loader, readerFactory, interfaceLambdaMethods, lambdaClass.getValue(), writer); reader.accept(visitor, 0); String filename = rewriter.unprefix(lambdaClass.getValue().desiredInternalName()) + ".class"; outputFileProvider.write(filename, writer.toByteArray()); } } }
From source file:org.killbill.billing.plugin.bitcoin.osgi.http.PaymentRequestServlet.java
private String createURL(HttpServletRequest req, String path, ImmutableMap<String, String> params) { final StringBuilder queryParamsBuilder = new StringBuilder("?"); for (final String key : params.keySet()) { queryParamsBuilder.append(key).append("=").append(params.get(key)).append("&"); }/* w w w. j a v a 2s . com*/ return req.getScheme() + "://" + req.getServerName() + ":" + req.getServerPort() + path + queryParamsBuilder.toString(); }
From source file:com.facebook.buck.features.project.intellij.IjProjectTemplateDataPreparer.java
public Optional<String> getFirstResourcePackageFromDependencies(IjModule module) { ImmutableMap<IjModule, DependencyType> deps = moduleGraph.getDependentModulesFor(module); for (IjModule dep : deps.keySet()) { Optional<IjModuleAndroidFacet> facet = dep.getAndroidFacet(); if (facet.isPresent()) { Optional<String> packageName = facet.get().getPackageName(); if (packageName.isPresent()) { return packageName; }/*from www . j av a 2 s .com*/ } } return Optional.empty(); }
From source file:com.facebook.buck.versions.ParallelVersionedTargetGraphBuilder.java
@Override protected VersionInfo getVersionInfo(TargetNode<?> node) { VersionInfo info = this.versionInfo.get(node.getBuildTarget()); if (info != null) { return info; }/*from www . j av a 2 s. co m*/ Map<BuildTarget, ImmutableSet<Version>> versionDomain = new HashMap<>(); Optional<TargetNode<VersionedAliasDescriptionArg>> versionedNode = TargetGraphVersionTransformations .getVersionedNode(node); if (versionedNode.isPresent()) { ImmutableMap<Version, BuildTarget> versions = versionedNode.get().getConstructorArg().getVersions(); // Merge in the versioned deps and the version domain. versionDomain.put(node.getBuildTarget(), versions.keySet()); // If this version has only one possible choice, there's no need to wrap the constraints from // it's transitive deps in an implication constraint. if (versions.size() == 1) { Map.Entry<Version, BuildTarget> ent = versions.entrySet().iterator().next(); VersionInfo depInfo = getVersionInfo(getNode(ent.getValue())); versionDomain.putAll(depInfo.getVersionDomain()); } else { // For each version choice, inherit the transitive constraints by wrapping them in an // implication dependent on the specific version that pulls them in. for (Map.Entry<Version, BuildTarget> ent : versions.entrySet()) { VersionInfo depInfo = getVersionInfo(getNode(ent.getValue())); versionDomain.putAll(depInfo.getVersionDomain()); } } } else { // Merge in the constraints and version domain/deps from transitive deps. for (BuildTarget depTarget : TargetGraphVersionTransformations.getDeps(typeCoercerFactory, node)) { TargetNode<?> dep = getNode(depTarget); if (TargetGraphVersionTransformations.isVersionPropagator(dep) || TargetGraphVersionTransformations.getVersionedNode(dep).isPresent()) { VersionInfo depInfo = getVersionInfo(dep); versionDomain.putAll(depInfo.getVersionDomain()); } } } info = VersionInfo.of(versionDomain); this.versionInfo.put(node.getBuildTarget(), info); return info; }
From source file:com.facebook.buck.android.exopackage.ExopackageInstaller.java
private void installFiles(String filesType, ImmutableMap<Path, Path> filesToInstall) throws Exception { try (SimplePerfEvent.Scope ignored = SimplePerfEvent.scope(eventBus, "multi_install_" + filesType); AutoCloseable ignored1 = device.createForward()) { // Make sure all the directories exist. filesToInstall.keySet().stream().map(p -> dataRoot.resolve(p).getParent()).distinct().forEach(p -> { try { device.mkDirP(p.toString()); } catch (Exception e) { throw new RuntimeException(e); }// ww w .j a v a 2s . c o m }); // Plan the installation. Map<Path, Path> installPaths = filesToInstall.entrySet().stream() .collect(Collectors.toMap(entry -> dataRoot.resolve(entry.getKey()), entry -> projectFilesystem.resolve(entry.getValue()))); // Install the files. device.installFiles(filesType, installPaths); } }
From source file:com.facebook.presto.metadata.Signature.java
@Nullable public Map<String, Type> bindTypeParameters(List<? extends Type> types, boolean allowCoercion, TypeManager typeManager) {// w w w. j a v a 2s . co m Map<String, Type> boundParameters = new HashMap<>(); ImmutableMap.Builder<String, TypeParameter> builder = ImmutableMap.builder(); for (TypeParameter parameter : typeParameters) { builder.put(parameter.getName(), parameter); } ImmutableMap<String, TypeParameter> parameters = builder.build(); if (!matchArguments(boundParameters, parameters, argumentTypes, types, allowCoercion, variableArity, typeManager)) { return null; } checkState(boundParameters.keySet().equals(parameters.keySet()), "%s matched arguments %s, but type parameters %s are still unbound", this, types, Sets.difference(parameters.keySet(), boundParameters.keySet())); return boundParameters; }
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 {/*from w w w. ja v a2 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.versions.VersionedTargetGraph.java
public VersionedTargetGraph(MutableDirectedGraph<TargetNode<?, ?>> graph, ImmutableMap<BuildTarget, TargetNode<?, ?>> index, ImmutableSet<TargetGroup> groups) { super(graph, index, groups); this.targetsToNodes = index; // Build the flavor map, which maps all unflavored targets to the flavors they have in the // graph. We sort the list of flavor sets from largest to smallest, so that look ups pick the // more flavored sets first. Map<UnflavoredBuildTarget, List<ImmutableSet<Flavor>>> flavorMapRawBuilder = new LinkedHashMap<>(); for (BuildTarget target : index.keySet()) { UnflavoredBuildTarget unflavoredTarget = target.getUnflavoredBuildTarget(); if (!flavorMapRawBuilder.containsKey(unflavoredTarget)) { flavorMapRawBuilder.put(unflavoredTarget, new ArrayList<>()); }/* w ww .j a v a 2 s . c om*/ flavorMapRawBuilder.get(unflavoredTarget).add(target.getFlavors()); } ImmutableMap.Builder<UnflavoredBuildTarget, ImmutableList<ImmutableSet<Flavor>>> flavorMapBuilder = ImmutableMap .builder(); for (Map.Entry<UnflavoredBuildTarget, List<ImmutableSet<Flavor>>> ent : flavorMapRawBuilder.entrySet()) { ent.getValue().sort((o1, o2) -> Integer.compare(o2.size(), o1.size())); flavorMapBuilder.put(ent.getKey(), ImmutableList.copyOf(ent.getValue())); } this.flavorMap = flavorMapBuilder.build(); }
From source file:org.codice.ddf.catalog.sourcepoller.Poller.java
/** * @throws IllegalStateException if unable to wait for polls * @throws InterruptedException if the current thread was interrupted * @throws CancellationException if the task to wait for the loader {@link Callable<V>} to be * complete was cancelled/*from w w w . j a v a 2 s. c om*/ * @throws ExecutionException if the the task to wait for the loader {@link Callable<V>} threw an * exception * @throws PollerException if unable to commit the value for any of the {@code itemsToPoll} */ private void doPollItems(long timeout, TimeUnit timeoutTimeUnit, ImmutableMap<K, Callable<V>> itemsToPoll) throws InterruptedException, ExecutionException, PollerException { removeNoncurrentKeysFromTheCache(itemsToPoll.keySet()); if (itemsToPoll.isEmpty()) { LOGGER.debug("itemsToPoll is empty. Nothing to poll"); return; } // Gather any exceptions while loading or committing new values final Map<K, Throwable> exceptions = new HashMap<>(); final CompletionService<Pair<K, Commitable>> completionService = new ExecutorCompletionService<>( pollTimeoutWatcherThreadPool); final int startedLoadsCount = startLoads(timeout, timeoutTimeUnit, itemsToPoll, completionService, exceptions); boolean interrupted = false; try { for (int i = 0; i < startedLoadsCount; i++) { // Use CompletionService#poll(long, TimeUnit) instead of CompletionService#take() even // though the timeout has already been accounted for in #load(K, Callable<V>, long, // TimeUnit) to prevent blocking forever // @throws InterruptedException if interrupted while waiting final Future<Pair<K, Commitable>> nextCompletedLoadFuture = completionService.poll(timeout, timeoutTimeUnit); if (nextCompletedLoadFuture == null) { final String message = String.format("Unable to wait for polls to finish within %d %s", timeout, timeoutTimeUnit); LOGGER.debug(message); throw new IllegalStateException(message); } // @throws CancellationException if the computation was cancelled // @throws ExecutionException if the computation threw an exception // @throws InterruptedException if the current thread was interrupted final Pair<K, Commitable> nextCompletedLoad = nextCompletedLoadFuture.get(); try { attemptToCommitLoadedValue(nextCompletedLoad.getKey(), nextCompletedLoad.getValue(), exceptions); } catch (InterruptedException e) { interrupted = true; } } } finally { if (interrupted) { Thread.currentThread().interrupt(); } } if (!exceptions.isEmpty()) { throw new PollerException(exceptions); } }
From source file:com.opengamma.strata.basics.currency.FxMatrixBuilder.java
private void retryDisjoints() { ensureCapacity(disjointRates.keySet().stream().flatMap(cp -> Stream.of(cp.getBase(), cp.getCounter()))); while (true) { int initialSize = disjointRates.size(); ImmutableMap<CurrencyPair, Double> addable = MapStream.of(disjointRates).filterKeys( pair -> currencies.containsKey(pair.getBase()) || currencies.containsKey(pair.getCounter())) .toMap();/*w w w .j a v a 2s. c o m*/ MapStream.of(addable).forEach((pair, rate) -> addNewRate(pair.getBase(), pair.getCounter(), rate)); addable.keySet().stream().forEach(disjointRates::remove); if (disjointRates.size() == initialSize) { // No effect so break out break; } } }