List of usage examples for com.google.common.collect ImmutableSet.Builder add
boolean add(E e);
From source file:com.google.errorprone.util.FindIdentifiers.java
/** * Finds the set of all bare variable identifiers in scope at the current location. Identifiers * are ordered by ascending distance/scope count from the current location to match shadowing * rules. That is, if two variables with the same simple names appear in the set, the one that * appears first in iteration order is the one you get if you use the bare name in the source * code.// www. j av a 2 s . co m * * <p>We do not report variables that would require a qualfied access. We also do not handle * wildcard imports. */ public static LinkedHashSet<VarSymbol> findAllIdents(VisitorState state) { ImmutableSet.Builder<VarSymbol> result = new ImmutableSet.Builder<>(); Tree prev = state.getPath().getLeaf(); for (Tree curr : state.getPath().getParentPath()) { switch (curr.getKind()) { case BLOCK: for (StatementTree stmt : ((BlockTree) curr).getStatements()) { if (stmt.equals(prev)) { break; } addIfVariable(stmt, result); } break; case METHOD: for (VariableTree param : ((MethodTree) curr).getParameters()) { result.add(ASTHelpers.getSymbol(param)); } break; case CATCH: result.add(ASTHelpers.getSymbol(((CatchTree) curr).getParameter())); break; case CLASS: case INTERFACE: case ENUM: case ANNOTATION_TYPE: // Collect fields declared in this class. If we are in a field initializer, only // include fields declared before this one. JLS 8.3.3 allows forward references if the // field is referred to by qualified name, but we don't support that. for (Tree member : ((ClassTree) curr).getMembers()) { if (member.equals(prev)) { break; } addIfVariable(member, result); } // Collect inherited fields. Type classType = ASTHelpers.getType(curr); com.sun.tools.javac.util.List<Type> superTypes = state.getTypes().closure(classType).tail; for (Type type : superTypes) { Scope scope = type.tsym.members(); ImmutableList.Builder<VarSymbol> varsList = new ImmutableList.Builder<VarSymbol>(); for (Symbol var : scope.getSymbols(VarSymbol.class::isInstance)) { varsList.add((VarSymbol) var); } result.addAll(varsList.build().reverse()); } break; case FOR_LOOP: addAllIfVariable(((ForLoopTree) curr).getInitializer(), result); break; case ENHANCED_FOR_LOOP: result.add(ASTHelpers.getSymbol(((EnhancedForLoopTree) curr).getVariable())); break; case TRY: TryTree tryTree = (TryTree) curr; boolean inResources = false; for (Tree resource : tryTree.getResources()) { if (resource.equals(prev)) { inResources = true; break; } } if (inResources) { // Case 1: we're in one of the resource declarations for (Tree resource : tryTree.getResources()) { if (resource.equals(prev)) { break; } addIfVariable(resource, result); } } else if (tryTree.getBlock().equals(prev)) { // Case 2: We're in the block (not a catch or finally) addAllIfVariable(tryTree.getResources(), result); } break; case COMPILATION_UNIT: for (ImportTree importTree : ((CompilationUnitTree) curr).getImports()) { if (importTree.isStatic() && importTree.getQualifiedIdentifier().getKind() == Kind.MEMBER_SELECT) { MemberSelectTree memberSelectTree = (MemberSelectTree) importTree.getQualifiedIdentifier(); Scope scope = state.getTypes().membersClosure( ASTHelpers.getType(memberSelectTree.getExpression()), /*skipInterface*/ false); for (Symbol var : scope.getSymbols(sym -> sym instanceof VarSymbol && sym.getSimpleName().equals(memberSelectTree.getIdentifier()))) { result.add((VarSymbol) var); } } } break; default: // other node types don't introduce variables break; } prev = curr; } // TODO(eaftan): switch out collector for ImmutableSet.toImmutableSet() return result.build().stream().filter(var -> isVisible(var, state.getPath())) .collect(Collectors.toCollection(LinkedHashSet::new)); }
From source file:com.facebook.buck.java.intellij.IjProjectTemplateDataPreparer.java
public static ImmutableSet<Path> createPackageLookupPathSet(IjModuleGraph moduleGraph) { ImmutableSet.Builder<Path> builder = ImmutableSet.builder(); for (IjModule module : moduleGraph.getModuleNodes()) { for (IjFolder folder : module.getFolders()) { if (!folder.getWantsPackagePrefix()) { continue; }/* w w w . j a v a 2 s . co m*/ Optional<Path> firstJavaFile = FluentIterable.from(folder.getInputs()) .filter(new Predicate<Path>() { @Override public boolean apply(Path input) { return input.getFileName().toString().endsWith(".java"); } }).first(); if (firstJavaFile.isPresent()) { builder.add(firstJavaFile.get()); } } } return builder.build(); }
From source file:zipkin2.storage.cassandra.v1.Indexer.java
@VisibleForTesting static ImmutableSetMultimap<PartitionKeyToTraceId, Long> entriesThatIncreaseGap( ConcurrentMap<PartitionKeyToTraceId, Pair> sharedState, ImmutableSetMultimap<PartitionKeyToTraceId, Long> updates) { ImmutableSet.Builder<PartitionKeyToTraceId> toUpdate = ImmutableSet.builder(); // Enter a loop that affects shared state when an update widens the time interval for a key. for (Map.Entry<PartitionKeyToTraceId, Long> input : updates.entries()) { PartitionKeyToTraceId key = input.getKey(); long timestamp = input.getValue(); for (;;) { Pair oldRange = sharedState.get(key); if (oldRange == null) { // Initial state is where this key has a single timestamp. oldRange = sharedState.putIfAbsent(key, new Pair(timestamp, timestamp)); // If there was no previous value, we need to update the index if (oldRange == null) { toUpdate.add(key); break; }//ww w . jav a 2 s . co m } long first = timestamp < oldRange.left ? timestamp : oldRange.left; long last = timestamp > oldRange.right ? timestamp : oldRange.right; Pair newRange = new Pair(first, last); if (oldRange.equals(newRange)) { break; // the current timestamp is contained } else if (sharedState.replace(key, oldRange, newRange)) { toUpdate.add(key); // The range was extended break; } } } // When the loop completes, we'll know one of our updates widened the interval of a trace, if // it is the first or last timestamp. By ignoring those between an existing interval, we can // end up with less Cassandra writes. Builder<PartitionKeyToTraceId, Long> result = ImmutableSetMultimap.builder(); for (PartitionKeyToTraceId needsUpdate : toUpdate.build()) { Pair firstLast = sharedState.get(needsUpdate); if (updates.containsEntry(needsUpdate, firstLast.left)) result.put(needsUpdate, firstLast.left); if (updates.containsEntry(needsUpdate, firstLast.right)) result.put(needsUpdate, firstLast.right); } return result.build(); }
From source file:io.prestosql.plugin.accumulo.AccumuloClient.java
/** * Gets a collection of Accumulo Range objects from the given Presto domain. * This maps the column constraints of the given Domain to an Accumulo Range scan. * * @param domain Domain, can be null (returns (-inf, +inf) Range) * @param serializer Instance of an {@link AccumuloRowSerializer} * @return A collection of Accumulo Range objects * @throws TableNotFoundException If the Accumulo table is not found *///from www. j a v a 2 s . c om public static Collection<Range> getRangesFromDomain(Optional<Domain> domain, AccumuloRowSerializer serializer) throws TableNotFoundException { // if we have no predicate pushdown, use the full range if (!domain.isPresent()) { return ImmutableSet.of(new Range()); } ImmutableSet.Builder<Range> rangeBuilder = ImmutableSet.builder(); for (io.prestosql.spi.predicate.Range range : domain.get().getValues().getRanges().getOrderedRanges()) { rangeBuilder.add(getRangeFromPrestoRange(range, serializer)); } return rangeBuilder.build(); }
From source file:com.google.testing.coverage.JacocoCoverageRunner.java
/** * Adds to the given {@link Set} the paths found in a txt file inside the given jar. * * <p>If a jar contains uninstrumented classes it will also contain a txt file with the paths of * each of these classes, one on each line. *///from w w w .java2 s .co m @VisibleForTesting static void addEntriesToExecPathsSet(File jar, ImmutableSet.Builder<String> execPathsSetBuilder) throws IOException { JarFile jarFile = new JarFile(jar); JarInputStream jarInputStream = new JarInputStream(new FileInputStream(jar)); for (JarEntry jarEntry = jarInputStream.getNextJarEntry(); jarEntry != null; jarEntry = jarInputStream .getNextJarEntry()) { String jarEntryName = jarEntry.getName(); if (jarEntryName.endsWith("-paths-for-coverage.txt")) { BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(jarFile.getInputStream(jarEntry), UTF_8)); String line; while ((line = bufferedReader.readLine()) != null) { execPathsSetBuilder.add(line); } } } }
From source file:com.google.devtools.build.lib.rules.android.ResourceFilterFactory.java
/** * Extracts filters from an AttributeMap, as a list of strings. * * <p>In BUILD files, string lists can be represented as a list of strings, a single * comma-separated string, or a combination of both. This method outputs a single list of * individual string values, which can then be passed directly to resource processing actions. * * @return the values of this attribute contained in the {@link AttributeMap}, as a list. *//*w w w .ja v a 2 s .c o m*/ private static ImmutableList<String> extractFilters(AttributeMap attrs, String attrName) { if (!hasAttr(attrs, attrName)) { return ImmutableList.<String>of(); } /* * To deal with edge cases involving placement of whitespace and multiple strings inside a * single item of the given list, manually build the list here rather than call something like * {@link RuleContext#getTokenizedStringListAttr}. * * Filter out all empty values, even those that were explicitly provided. Paying attention to * empty values is never helpful: even if code handled them correctly (and not all of it does) * empty filter values result in all resources matching the empty filter, meaning that filtering * does nothing (even if non-empty filters were also provided). */ List<String> rawValues = attrs.get(attrName, Type.STRING_LIST); // Use an ImmutableSet to remove duplicate values ImmutableSet.Builder<String> builder = ImmutableSet.builder(); for (String rawValue : rawValues) { if (rawValue.contains(",")) { for (String token : rawValue.split(",")) { if (!token.trim().isEmpty()) { builder.add(token.trim()); } } } else if (!rawValue.isEmpty()) { builder.add(rawValue); } } // Create a sorted copy so that ResourceFilterFactory objects with the same filters are treated // the same regardless of the ordering of those filters. return ImmutableList.sortedCopyOf(builder.build()); }
From source file:com.pinterest.pinlater.commons.config.ConfigFileServerSet.java
protected static ImmutableSet<ServiceInstance> readServerSet(byte[] fileContent) throws IOException { ImmutableSet.Builder<ServiceInstance> builder = new ImmutableSet.Builder<ServiceInstance>(); InputStream stream = new ByteArrayInputStream(fileContent); BufferedReader reader = new BufferedReader(new InputStreamReader(stream)); while (true) { String line = reader.readLine(); if (line == null) { // EOF. break; } else if (line.isEmpty()) { // Skip empty lines. continue; }/*from ww w . j a v a 2 s.c o m*/ // We expect each line to be of the form "hostname:port". Note that host names can // contain ':' themselves (e.g. ipv6 addresses). int index = line.lastIndexOf(':'); Preconditions.checkArgument(index > 0 && index < line.length() - 1); String host = line.substring(0, index); int port = Integer.parseInt(line.substring(index + 1)); builder.add(new ServiceInstance(new Endpoint(host, port), // endpoint Collections.<String, Endpoint>emptyMap(), // additional endpoints Status.ALIVE)); // status } return builder.build(); }
From source file:com.facebook.presto.accumulo.AccumuloClient.java
/** * Gets a collection of Accumulo Range objects from the given Presto domain. * This maps the column constraints of the given Domain to an Accumulo Range scan. * * @param domain Domain, can be null (returns (-inf, +inf) Range) * @param serializer Instance of an {@link AccumuloRowSerializer} * @return A collection of Accumulo Range objects * @throws TableNotFoundException If the Accumulo table is not found *//*from w w w . ja va 2 s.c om*/ public static Collection<Range> getRangesFromDomain(Optional<Domain> domain, AccumuloRowSerializer serializer) throws TableNotFoundException { // if we have no predicate pushdown, use the full range if (!domain.isPresent()) { return ImmutableSet.of(new Range()); } ImmutableSet.Builder<Range> rangeBuilder = ImmutableSet.builder(); for (com.facebook.presto.spi.predicate.Range range : domain.get().getValues().getRanges() .getOrderedRanges()) { rangeBuilder.add(getRangeFromPrestoRange(range, serializer)); } return rangeBuilder.build(); }
From source file:dagger.internal.codegen.Binding.java
private static Set<String> nonPublicPackageUse(TypeMirror typeMirror) { ImmutableSet.Builder<String> packages = ImmutableSet.builder(); typeMirror.accept(new SimpleTypeVisitor6<Void, ImmutableSet.Builder<String>>() { @Override/*from ww w . j a va2s.c om*/ public Void visitArray(ArrayType t, ImmutableSet.Builder<String> p) { return t.getComponentType().accept(this, p); } @Override public Void visitDeclared(DeclaredType t, ImmutableSet.Builder<String> p) { for (TypeMirror typeArgument : t.getTypeArguments()) { typeArgument.accept(this, p); } // TODO(gak): address public nested types in non-public types TypeElement typeElement = MoreElements.asType(t.asElement()); if (!typeElement.getModifiers().contains(PUBLIC)) { PackageElement elementPackage = MoreElements.getPackage(typeElement); Name qualifiedName = elementPackage.getQualifiedName(); p.add(qualifiedName.toString()); } // Also make sure enclosing types are visible, otherwise we're fooled by // class Foo { public class Bar } // (Note: we can't use t.getEnclosingType() because it doesn't work!) typeElement.getEnclosingElement().asType().accept(this, p); return null; } @Override public Void visitWildcard(WildcardType t, ImmutableSet.Builder<String> p) { if (t.getExtendsBound() != null) { t.getExtendsBound().accept(this, p); } if (t.getSuperBound() != null) { t.getSuperBound().accept(this, p); } return null; } }, packages); return packages.build(); }
From source file:com.saharw.objectpool.common.MoreTypes.java
/** * Returns the set of {@linkplain TypeElement types} that are referenced by the given * {@link TypeMirror}.//w w w . ja v a2s. co m */ public static ImmutableSet<TypeElement> referencedTypes(TypeMirror type) { checkNotNull(type); ImmutableSet.Builder<TypeElement> elements = ImmutableSet.builder(); type.accept(new SimpleTypeVisitor6<Void, ImmutableSet.Builder<TypeElement>>() { @Override public Void visitArray(ArrayType t, ImmutableSet.Builder<TypeElement> p) { t.getComponentType().accept(this, p); return null; } @Override public Void visitDeclared(DeclaredType t, ImmutableSet.Builder<TypeElement> p) { p.add(MoreElements.asType(t.asElement())); for (TypeMirror typeArgument : t.getTypeArguments()) { typeArgument.accept(this, p); } return null; } @Override public Void visitTypeVariable(TypeVariable t, ImmutableSet.Builder<TypeElement> p) { t.getLowerBound().accept(this, p); t.getUpperBound().accept(this, p); return null; } @Override public Void visitWildcard(WildcardType t, ImmutableSet.Builder<TypeElement> p) { TypeMirror extendsBound = t.getExtendsBound(); if (extendsBound != null) { extendsBound.accept(this, p); } TypeMirror superBound = t.getSuperBound(); if (superBound != null) { superBound.accept(this, p); } return null; } }, elements); return elements.build(); }