Example usage for com.google.common.collect ImmutableSet.Builder add

List of usage examples for com.google.common.collect ImmutableSet.Builder add

Introduction

In this page you can find the example usage for com.google.common.collect ImmutableSet.Builder add.

Prototype

boolean add(E e);

Source Link

Document

Adds the specified element to this set if it is not already present (optional operation).

Usage

From source file:org.apache.abdera2.common.misc.MoreFunctions.java

public static <T, X> Set<X> seteach(T[] i, Function<T, X> apply) {
    ImmutableSet.Builder<X> list = ImmutableSet.builder();
    for (T t : i) {
        try {//from w w  w .j a  v a  2s . c  o m
            list.add(apply.apply(t));
        } catch (Throwable e) {
            throw ExceptionHelper.propogate(e);
        }
    }
    return list.build();
}

From source file:com.google.api.codegen.MethodConfig.java

/**
 * Creates an instance of MethodConfig based on MethodConfigProto, linking it up with the provided
 * method. On errors, null will be returned, and diagnostics are reported to the diag collector.
 *//*from w  ww  .  jav  a 2 s  .  c  om*/
@Nullable
public static MethodConfig createMethodConfig(DiagCollector diagCollector,
        final MethodConfigProto methodConfigProto, Method method, ImmutableSet<String> retryCodesConfigNames,
        ImmutableSet<String> retryParamsConfigNames) {

    boolean error = false;

    PageStreamingConfig pageStreaming;
    if (PageStreamingConfigProto.getDefaultInstance().equals(methodConfigProto.getPageStreaming())) {
        pageStreaming = null;
    } else {
        pageStreaming = PageStreamingConfig.createPageStreaming(diagCollector,
                methodConfigProto.getPageStreaming(), method);
        if (pageStreaming == null) {
            error = true;
        }
    }

    FlatteningConfig flattening;
    if (FlatteningConfigProto.getDefaultInstance().equals(methodConfigProto.getFlattening())) {
        flattening = null;
    } else {
        flattening = FlatteningConfig.createFlattening(diagCollector, methodConfigProto.getFlattening(),
                method);
        if (flattening == null) {
            error = true;
        }
    }

    BundlingConfig bundling;
    if (BundlingConfigProto.getDefaultInstance().equals(methodConfigProto.getBundling())) {
        bundling = null;
    } else {
        bundling = BundlingConfig.createBundling(diagCollector, methodConfigProto.getBundling(), method);
        if (bundling == null) {
            error = true;
        }
    }

    String retryCodesName = methodConfigProto.getRetryCodesName();
    if (!retryCodesName.isEmpty() && !retryCodesConfigNames.contains(retryCodesName)) {
        diagCollector.addDiag(Diag.error(SimpleLocation.TOPLEVEL,
                "Retry codes config used but not defined: '%s' (in method %s)", retryCodesName,
                method.getFullName()));
        error = true;
    }

    String retryParamsName = methodConfigProto.getRetryParamsName();
    if (!retryParamsConfigNames.isEmpty() && !retryParamsConfigNames.contains(retryParamsName)) {
        diagCollector.addDiag(Diag.error(SimpleLocation.TOPLEVEL,
                "Retry parameters config used but not defined: %s (in method %s)", retryParamsName,
                method.getFullName()));
        error = true;
    }

    Duration timeout = Duration.millis(methodConfigProto.getTimeoutMillis());
    if (timeout.getMillis() <= 0) {
        diagCollector.addDiag(Diag.error(SimpleLocation.TOPLEVEL,
                "Default timeout not found or has invalid value (in method %s)", method.getFullName()));
        error = true;
    }

    boolean hasRequestObjectMethod = methodConfigProto.getRequestObjectMethod();

    List<String> requiredFieldNames = methodConfigProto.getRequiredFieldsList();
    ImmutableSet.Builder<Field> builder = ImmutableSet.builder();
    for (String fieldName : requiredFieldNames) {
        Field requiredField = method.getInputMessage().lookupField(fieldName);
        if (requiredField != null) {
            builder.add(requiredField);
        } else {
            Diag.error(SimpleLocation.TOPLEVEL, "Required field '%s' not found (in method %s)", fieldName,
                    method.getFullName());
            error = true;
        }
    }
    Set<Field> requiredFields = builder.build();

    Iterable<Field> optionalFields = Iterables.filter(method.getInputType().getMessageType().getFields(),
            new Predicate<Field>() {
                @Override
                public boolean apply(Field input) {
                    return !(methodConfigProto.getRequiredFieldsList().contains(input.getSimpleName()));
                }
            });

    ImmutableMap<String, String> fieldNamePatterns = ImmutableMap
            .copyOf(methodConfigProto.getFieldNamePatterns());

    List<String> sampleCodeInitFields = new ArrayList<>();
    sampleCodeInitFields.addAll(methodConfigProto.getRequiredFieldsList());
    sampleCodeInitFields.addAll(methodConfigProto.getSampleCodeInitFieldsList());

    if (error) {
        return null;
    } else {
        return new MethodConfig(pageStreaming, flattening, retryCodesName, retryParamsName, timeout, bundling,
                hasRequestObjectMethod, requiredFields, optionalFields, fieldNamePatterns,
                sampleCodeInitFields);
    }
}

From source file:org.gradle.internal.ImmutableActionSet.java

private static <T> void unpackAction(Action<? super T> action,
        ImmutableSet.Builder<Action<? super T>> builder) {
    if (action instanceof ImmutableActionSet) {
        ImmutableActionSet<T> immutableSet = (ImmutableActionSet<T>) action;
        immutableSet.unpackInto(builder);
    } else {//w  w w. j a v a  2s  .  com
        builder.add(action);
    }
}

From source file:com.facebook.buck.apple.AppleLibraryDescriptionSwiftEnhancer.java

/**
 * Returns transitive preprocessor inputs excluding those from the swift delegate of the given
 * CxxLibrary./* www.jav a 2s.  co  m*/
 */
public static ImmutableSet<CxxPreprocessorInput> getPreprocessorInputsForAppleLibrary(BuildTarget target,
        ActionGraphBuilder graphBuilder, CxxPlatform platform, AppleNativeTargetDescriptionArg arg) {
    CxxLibrary lib = (CxxLibrary) graphBuilder.requireRule(target.withFlavors());
    ImmutableMap<BuildTarget, CxxPreprocessorInput> transitiveMap = TransitiveCxxPreprocessorInputCache
            .computeTransitiveCxxToPreprocessorInputMap(platform, lib, false, graphBuilder);

    ImmutableSet.Builder<CxxPreprocessorInput> builder = ImmutableSet.builder();
    builder.addAll(transitiveMap.values());
    if (arg.isModular()) {
        Optional<CxxPreprocessorInput> underlyingModule = AppleLibraryDescription
                .underlyingModuleCxxPreprocessorInput(target, graphBuilder, platform);
        underlyingModule.ifPresent(builder::add);
    } else {
        builder.add(lib.getPublicCxxPreprocessorInputExcludingDelegate(platform, graphBuilder));
    }

    return builder.build();
}

From source file:com.facebook.buck.cli.TargetsCommandOptions.java

/**
 * Filter files under the project root, and convert to canonical relative path style.
 * For example, the project root is /project,
 * 1. file path /project/./src/com/facebook/./test/../Test.java will be converted to
 *    src/com/facebook/Test.java//from   w  w w.j ava  2  s  . co  m
 * 2. file path /otherproject/src/com/facebook/Test.java will be ignored.
 */
public static ImmutableSet<String> getCanonicalFilesUnderProjectRoot(File projectRoot,
        ImmutableSet<String> nonCanonicalFilePaths) throws IOException {
    ImmutableSet.Builder<String> builder = ImmutableSet.builder();
    String projectRootCanonicalFullPathWithEndSlash = projectRoot.getCanonicalPath() + File.separator;
    for (String filePath : nonCanonicalFilePaths) {
        String canonicalFullPath = new File(filePath).getCanonicalPath();

        // Ignore files that aren't under project root.
        if (canonicalFullPath.startsWith(projectRootCanonicalFullPathWithEndSlash)) {
            builder.add(MorePaths
                    .newPathInstance(
                            canonicalFullPath.substring(projectRootCanonicalFullPathWithEndSlash.length()))
                    .toString());
        }
    }
    return builder.build();
}

From source file:com.facebook.buck.util.MorePosixFilePermissions.java

/**
 * Return a new set of permissions which include execute permission for each of the
 * roles that already have read permissions (e.g. 0606 => 0707).
 *//*w w w.j a  va 2 s . co m*/
public static ImmutableSet<PosixFilePermission> addExecutePermissionsIfReadable(
        Set<PosixFilePermission> permissions) {

    ImmutableSet.Builder<PosixFilePermission> newPermissions = ImmutableSet.builder();

    // The new permissions are a superset of the current ones.
    newPermissions.addAll(permissions);

    // If we see a read permission for the given role, add in the corresponding
    // execute permission.
    for (ImmutableMap.Entry<PosixFilePermission, PosixFilePermission> ent : READ_TO_EXECUTE_MAP.entrySet()) {
        if (permissions.contains(ent.getKey())) {
            newPermissions.add(ent.getValue());
        }
    }

    return newPermissions.build();
}

From source file:com.google.auto.value.extension.memoized.MemoizeExtension.java

private static ImmutableSet<ExecutableElement> memoizedMethods(Context context) {
    ImmutableSet.Builder<ExecutableElement> memoizedMethods = ImmutableSet.builder();
    for (ExecutableElement method : methodsIn(context.autoValueClass().getEnclosedElements())) {
        if (isAnnotationPresent(method, Memoized.class)) {
            memoizedMethods.add(method);
        }/*  w  ww  . j  a v a2s  . c  o m*/
    }
    return memoizedMethods.build();
}

From source file:org.lenskit.LenskitInfo.java

private static Set<String> loadRevisionSet() {
    ImmutableSet.Builder<String> revisions = ImmutableSet.builder();
    InputStream input = LenskitInfo.class.getResourceAsStream("/META-INF/lenskit/git-commits.lst");
    if (input != null) {
        try (Reader reader = new InputStreamReader(input, Charsets.UTF_8);
                BufferedReader lines = new BufferedReader(reader)) {
            String line;/*  w  ww  . j a v a  2 s  .c  o m*/
            while ((line = lines.readLine()) != null) {
                revisions.add(StringUtils.trim(line));
            }
        } catch (IOException e) {
            logger.warn("Could not read Git revision list", e);
        } finally {
            try {
                input.close();
            } catch (IOException e) {
                logger.error("error closing git-commit list", e);
            }
        }
    } else {
        logger.warn("cannot find LensKit revision list");
    }
    Set<String> revset = revisions.build();
    logger.debug("have {} active revisions", revset.size());
    return revset;
}

From source file:com.jeffreybosboom.lyne.Solver.java

/**
 * Returns the paths through the given solved puzzle, one per color, or null
 * if the solution paths are unsatisfying.
 * @param puzzle a solved puzzle/*from  www  .j  av a2 s  . c o  m*/
 * @return the solution paths, one per color, or null
 */
private static Set<List<Node>> solutionPaths(Puzzle puzzle) {
    puzzle.getClass();
    checkArgument(puzzle.edges().allMatch(a -> puzzle.possibilities(a.first, a.second).size() == 1));
    ImmutableSet.Builder<List<Node>> pathsBuilder = ImmutableSet.builder();
    for (Iterator<Pair<Node, Node>> it = puzzle.terminals().iterator(); it.hasNext();) {
        Pair<Node, Node> pair = it.next();
        List<Node> path = new ArrayList<>();
        path.add(pair.first);
        path = findPath(puzzle, path, pair.second, new HashSet<>());
        if (path == null)
            return null;
        pathsBuilder.add(path);
    }
    ImmutableSet<List<Node>> paths = pathsBuilder.build();
    Multiset<Node> counts = HashMultiset.create();
    paths.stream().forEachOrdered(counts::addAll);
    //ensure each node appears enough times over all the paths
    //TODO: we check colored node appearances in findPath, so this could be
    //just octagons?
    if (!puzzle.nodes().allMatch(n -> counts.count(n) == (n.desiredEdges() + 1) / 2))
        return null;
    return paths;
}

From source file:com.google.devtools.build.buildjar.genclass.GenClass.java

/**
 * For each top-level class in the compilation, determine the path prefix of classes corresponding
 * to that compilation unit./*w ww. java2s.c om*/
 *
 * <p>Prefixes are used to correctly handle inner classes, e.g. the top-level class "c.g.Foo" may
 * correspond to "c/g/Foo.class" and also "c/g/Foo$Inner.class" or "c/g/Foo$0.class".
 */
@VisibleForTesting
static ImmutableSet<String> getGeneratedPrefixes(Manifest manifest) {
    ImmutableSet.Builder<String> prefixes = ImmutableSet.builder();
    for (CompilationUnit unit : manifest.getCompilationUnitList()) {
        if (!unit.getGeneratedByAnnotationProcessor()) {
            continue;
        }
        String pkg;
        if (unit.hasPkg()) {
            pkg = unit.getPkg().replace('.', '/') + "/";
        } else {
            pkg = "";
        }
        for (String toplevel : unit.getTopLevelList()) {
            prefixes.add(pkg + toplevel);
        }
    }
    return prefixes.build();
}