List of usage examples for com.google.common.collect ImmutableSet stream
default Stream<E> stream()
From source file:com.google.errorprone.bugpatterns.InconsistentCapitalization.java
@Override public Description matchClass(ClassTree tree, VisitorState state) { ImmutableSet<Symbol> fields = FieldScanner.findFields(tree); if (fields.isEmpty()) { return Description.NO_MATCH; }/*from www. j a v a 2 s . co m*/ ImmutableMap<String, Symbol> fieldNamesMap = fields.stream() .collect(toImmutableMap(symbol -> Ascii.toLowerCase(symbol.toString()), x -> x, (x, y) -> x)); ImmutableMap<TreePath, Symbol> matchedParameters = MatchingParametersScanner .findMatchingParameters(fieldNamesMap, state.getPath()); if (matchedParameters.isEmpty()) { return Description.NO_MATCH; } for (Entry<TreePath, Symbol> entry : matchedParameters.entrySet()) { TreePath parameterPath = entry.getKey(); Symbol field = entry.getValue(); String fieldName = field.getSimpleName().toString(); VariableTree parameterTree = (VariableTree) parameterPath.getLeaf(); SuggestedFix.Builder fix = SuggestedFix.builder() .merge(SuggestedFixes.renameVariable(parameterTree, fieldName, state)); if (parameterPath.getParentPath() != null) { String qualifiedName = getExplicitQualification(parameterPath, tree, state) + field.getSimpleName(); // If the field was accessed in a non-qualified way, by renaming the parameter this may // cause clashes with it. Thus, it is required to qualify all uses of the field within the // parameter's scope just in case. parameterPath.getParentPath().getLeaf().accept(new TreeScanner<Void, Void>() { @Override public Void visitIdentifier(IdentifierTree tree, Void unused) { if (field.equals(ASTHelpers.getSymbol(tree))) { fix.replace(tree, qualifiedName); } return null; } }, null); } state.reportMatch( buildDescription(parameterPath.getLeaf()) .setMessage(String.format( "Found the field '%s' with the same name as the parameter '%s' but with " + "different capitalization.", fieldName, ((VariableTree) parameterPath.getLeaf()).getName())) .addFix(fix.build()).build()); } return Description.NO_MATCH; }
From source file:com.facebook.buck.features.project.intellij.IjProjectCommandHelper.java
private ImmutableSet<BuildTarget> getTargetsWithAnnotations(TargetGraph targetGraph, ImmutableSet<BuildTarget> buildTargets) { return buildTargets.stream().filter(input -> { TargetNode<?> targetNode = targetGraph.get(input); return targetNode != null && isTargetWithAnnotations(targetNode); }).collect(ImmutableSet.toImmutableSet()); }
From source file:com.facebook.buck.distributed.DistBuildArtifactCacheImpl.java
@Override public synchronized void prewarmRemoteContains(ImmutableSet<BuildRule> rulesToBeChecked) { @SuppressWarnings("PMD.PrematureDeclaration") Stopwatch stopwatch = Stopwatch.createStarted(); Set<BuildRule> unseenRules = rulesToBeChecked.stream() .filter(rule -> !remoteCacheContainsFutures.containsKey(rule)).collect(Collectors.toSet()); if (unseenRules.isEmpty()) { return;/*from www.j a v a 2 s . com*/ } LOG.info("Checking remote cache for [%d] new rules.", unseenRules.size()); Map<BuildRule, ListenableFuture<RuleKey>> rulesToKeys = Maps.asMap(unseenRules, rule -> ruleKeyCalculator.calculate(eventBus, rule)); ListenableFuture<Map<RuleKey, CacheResult>> keysToCacheResultFuture = Futures .transformAsync(Futures.allAsList(rulesToKeys.values()), ruleKeys -> { LOG.info("Computing RuleKeys for %d new rules took %dms.", unseenRules.size(), stopwatch.elapsed(TimeUnit.MILLISECONDS)); stopwatch.reset(); stopwatch.start(); return multiContainsAsync(ruleKeys); }, executorService); Map<BuildRule, ListenableFuture<Boolean>> containsResultsForUnseenRules = Maps .asMap(unseenRules, rule -> Futures.transform(keysToCacheResultFuture, keysToCacheResult -> Objects .requireNonNull(keysToCacheResult.get(Futures.getUnchecked(rulesToKeys.get(rule)))) .getType().isSuccess(), MoreExecutors.directExecutor())); remoteCacheContainsFutures.putAll(containsResultsForUnseenRules); Futures.allAsList(containsResultsForUnseenRules.values()) .addListener(() -> LOG.info("Checking the remote cache for %d rules took %dms.", unseenRules.size(), stopwatch.elapsed(TimeUnit.MILLISECONDS)), MoreExecutors.directExecutor()); }
From source file:com.facebook.buck.tools.consistency.RuleKeyFileParser.java
/** * Parse a thrift compact serialized file * * @param filename The name of the file//from w ww .ja va 2s . c om * @param targetNames The name of the targets that should be found * @return A {@link ParsedRuleKeyFile} object that all deserialized rules, and the rule key hash * of the specified target * @throws ParseException If an IO or serialization error occurs, or if the target could not be * found in the file */ public ParsedRuleKeyFile parseFile(Path filename, ImmutableSet<String> targetNames) throws ParseException { // If //foo/bar/... is passed in, we want to find all targets that start with // //foo/bar, and that are of the right type, and add them as root nodes ImmutableList<String> recursiveTargetPrefixes = targetNames.stream() .filter(name -> name.endsWith("/...") || name.endsWith(":")).map(name -> { int idx = name.lastIndexOf("/..."); if (idx != -1) { return name.substring(0, idx); } else { return name; } }).collect(ImmutableList.toImmutableList()); long startNanos = System.nanoTime(); int initialSize; try { initialSize = Math.toIntExact(filename.toFile().length() / THRIFT_STRUCT_SIZE); } catch (ArithmeticException e) { throw new ParseException(e, filename, "File size is too large (>2.1 billion objects would be deserialized"); } ImmutableMap.Builder<String, RuleKeyNode> rootNodesBuilder = ImmutableMap.builder(); Map<String, RuleKeyNode> rules = new HashMap<>(); try { reader.readFile(filename, ruleKey -> { RuleKeyNode newNode = new RuleKeyNode(ruleKey); if ("DEFAULT".equals(ruleKey.type)) { // If either a specific rule is present, or if the target starts with one of the // prefixes if (targetNames.contains(ruleKey.name) || recursiveTargetPrefixes.stream() .filter(prefix -> ruleKey.name.startsWith(prefix)).findFirst().isPresent()) { rootNodesBuilder.put(ruleKey.name, newNode); } } RuleKeyNode oldValue = rules.put(ruleKey.key, newNode); if (oldValue != null && !oldValue.ruleKey.equals(newNode.ruleKey)) { throw new RuntimeException(new ParseException(filename, "Found two rules with the same key, but different values. Key: %s, first value: " + "%s, second value: %s", ruleKey.key, oldValue.ruleKey, newNode.ruleKey)); } return false; }); } catch (RuntimeException e) { if (e.getCause() instanceof ParseException) { throw (ParseException) e.getCause(); } } ImmutableMap<String, RuleKeyNode> rootNodes = rootNodesBuilder.build(); for (String targetName : targetNames) { if (!targetName.endsWith("/...") && !targetName.endsWith(":") && !rootNodes.containsKey(targetName)) { throw new ParseException(filename, "Could not find %s in %s", targetName, filename); } } Duration runtime = Duration.ofNanos(System.nanoTime() - startNanos); return new ParsedRuleKeyFile(filename, rootNodes, rules, runtime); }
From source file:com.facebook.buck.android.packageable.AndroidPackageableCollector.java
public AndroidPackageableCollection build() { collectionBuilder.setBuildConfigs(ImmutableMap.copyOf(buildConfigs)); ImmutableSet<HasJavaClassHashes> javaClassProviders = javaClassHashesProviders.build(); collectionBuilder.addAllJavaLibrariesToDex(javaClassProviders.stream() .map(HasJavaClassHashes::getBuildTarget).collect(ImmutableSet.toImmutableSet())); collectionBuilder.setClassNamesToHashesSupplier(MoreSuppliers.memoize(() -> { Builder<String, HashCode> builder = ImmutableMap.builder(); for (HasJavaClassHashes hasJavaClassHashes : javaClassProviders) { builder.putAll(hasJavaClassHashes.getClassNamesToHashes()); }// w ww . j a v a2 s.c om return builder.build(); })::get); apkModuleGraph.getAPKModules().forEach(apkModule -> collectionBuilder.putResourceDetails(apkModule, resourceCollectors.get(apkModule).getResourceDetails())); return collectionBuilder.build(); }
From source file:com.facebook.buck.features.go.GoProjectCommandHelper.java
private ExitCode runBuild(ImmutableSet<BuildTarget> targets) throws Exception { BuildCommand buildCommand = new BuildCommand( targets.stream().map(Object::toString).collect(ImmutableList.toImmutableList())); buildCommand.setKeepGoing(true);//www. j a v a 2 s. c om return buildCommand.run(params); }
From source file:com.jeffreybosboom.lyne.Puzzle.java
/** * Returns a Puzzle with the given possibility removed from the edge between * the given nodes. If the possibility is already not possible, this Puzzle * is returned. If this removes the last possibility for this edge, * a ContradictionException is thrown./*from w w w . j a va 2s . c om*/ */ public Puzzle remove(Node a, Node b, Node.Kind possibility) { Pair<Node, Node> p = Pair.sorted(a, b); ImmutableSet<Node.Kind> possibilities = possibilities(a, b); if (!possibilities.contains(possibility)) return this; if (possibilities.size() == 1) throw new ContradictionException(); ImmutableSet<Node.Kind> newSet = ImmutableSet .copyOf(possibilities.stream().filter(x -> x != possibility).iterator()); return withEdgeSet(p, newSet); }
From source file:com.facebook.buck.jvm.java.AbstractUnusedDependenciesFinder.java
private void processUnusedDependencies(MessageHandler messageHandler, String dependencyType, ImmutableSet<UnflavoredBuildTarget> unusedDependencies) { BuildTarget buildTarget = getBuildTarget(); String commandTemplate = "buildozer 'remove %s %s' %s"; String commands = Joiner.on('\n') .join(unusedDependencies.stream() .map(dep -> String.format(commandTemplate, dependencyType, dep, buildTarget)) .collect(Collectors.toList())); String messageTemplate = "Target %s is declared with unused targets in %s: \n%s\n\n" + "Use the following commands to remove them: \n%s\n"; String deps = Joiner.on('\n').join(unusedDependencies); String message = String.format(messageTemplate, buildTarget, dependencyType, deps, commands); messageHandler.processMessage(message); }
From source file:com.facebook.buck.apple.AppleBinaryDescription.java
@Override public Optional<ImmutableSet<FlavorDomain<?>>> flavorDomains() { ImmutableSet.Builder<FlavorDomain<?>> builder = ImmutableSet.builder(); ImmutableSet<FlavorDomain<?>> localDomains = ImmutableSet.of(AppleDebugFormat.FLAVOR_DOMAIN); builder.addAll(localDomains);/*from w ww .j a v a2s. c o m*/ delegate.flavorDomains().ifPresent(domains -> builder.addAll(domains)); swiftDelegate.flavorDomains().ifPresent(domains -> builder.addAll(domains)); ImmutableSet<FlavorDomain<?>> result = builder.build(); // Drop StripStyle because it's overridden by AppleDebugFormat result = result.stream().filter(domain -> !domain.equals(StripStyle.FLAVOR_DOMAIN)) .collect(MoreCollectors.toImmutableSet()); return Optional.of(result); }
From source file:grakn.core.graql.gremlin.ConjunctionQuery.java
/** * @param patternConjunction a pattern containing no disjunctions to find in the graph *///from w ww.j ava2s .c o m ConjunctionQuery(Conjunction<Statement> patternConjunction, TransactionOLTP tx) { statements = patternConjunction.getPatterns(); if (statements.size() == 0) { throw GraqlException.noPatterns(); } ImmutableSet<EquivalentFragmentSet> fragmentSets = statements.stream() .flatMap(statements -> equivalentFragmentSetsRecursive(statements)) .collect(ImmutableSet.toImmutableSet()); // Get all variable names mentioned in non-starting, non-comparing fragments (these should have vars bound elsewhere too) Set<Variable> names = fragmentSets.stream().flatMap(EquivalentFragmentSet::stream) .filter(fragment -> !fragment.validStartIfDisconnected() && !(fragment instanceof ValueFragment) && !(fragment instanceof NeqFragment)) .flatMap(fragment -> fragment.vars().stream()).collect(ImmutableSet.toImmutableSet()); // Get all dependencies fragments have on certain variables existing Set<Variable> dependencies = fragmentSets.stream().flatMap(EquivalentFragmentSet::stream) .flatMap(fragment -> fragment.dependencies().stream()).collect(ImmutableSet.toImmutableSet()); Set<Variable> validNames = Sets.difference(names, dependencies); // Filter out any non-essential starting fragments (because other fragments refer to their starting variable) Set<EquivalentFragmentSet> initialEquivalentFragmentSets = fragmentSets.stream() .filter(set -> set.stream().anyMatch( fragment -> !fragment.validStartIfDisconnected() || !validNames.contains(fragment.start()))) .collect(toSet()); // Apply final optimisations EquivalentFragmentSets.optimiseFragmentSets(initialEquivalentFragmentSets, tx); this.equivalentFragmentSets = ImmutableSet.copyOf(initialEquivalentFragmentSets); }