Example usage for com.google.common.collect ImmutableList size

List of usage examples for com.google.common.collect ImmutableList size

Introduction

In this page you can find the example usage for com.google.common.collect ImmutableList size.

Prototype

int size();

Source Link

Document

Returns the number of elements in this list.

Usage

From source file:org.apache.beam.sdk.extensions.sql.impl.rel.BeamValuesRel.java

@Override
public PCollection<BeamRecord> buildBeamPipeline(PCollectionTuple inputPCollections, BeamSqlEnv sqlEnv)
        throws Exception {
    List<BeamRecord> rows = new ArrayList<>(tuples.size());
    String stageName = BeamSqlRelUtils.getStageName(this);
    if (tuples.isEmpty()) {
        throw new IllegalStateException("Values with empty tuples!");
    }//from   w w  w  .  ja v  a 2  s  .  com

    BeamRecordSqlType beamSQLRowType = CalciteUtils.toBeamRowType(this.getRowType());
    for (ImmutableList<RexLiteral> tuple : tuples) {
        List<Object> fieldsValue = new ArrayList<>(beamSQLRowType.getFieldCount());
        for (int i = 0; i < tuple.size(); i++) {
            fieldsValue.add(BeamTableUtils.autoCastField(beamSQLRowType.getFieldTypeByIndex(i),
                    tuple.get(i).getValue()));
        }
        rows.add(new BeamRecord(beamSQLRowType, fieldsValue));
    }

    return inputPCollections.getPipeline().apply(stageName, Create.of(rows))
            .setCoder(beamSQLRowType.getRecordCoder());
}

From source file:com.facebook.buck.query.AttrFilterFunction.java

@Override
public Set<QueryTarget> eval(QueryEnvironment env, ImmutableList<Argument> args,
        ListeningExecutorService executor) throws QueryException, InterruptedException {
    QueryExpression argument = args.get(args.size() - 1).getExpression();
    String attr = CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, args.get(0).getWord());

    final String attrValue = args.get(1).getWord();
    final Predicate<Object> predicate = input -> attrValue.equals(input.toString());

    Set<QueryTarget> result = new LinkedHashSet<>();
    for (QueryTarget target : argument.eval(env, executor)) {
        ImmutableSet<Object> matchingObjects = env.filterAttributeContents(target, attr, predicate);
        if (!matchingObjects.isEmpty()) {
            result.add(target);/*www .  j a v  a2s. c om*/
        }
    }
    return result;
}

From source file:edu.mit.streamjit.impl.compiler2.SubsetAllocationStrategy.java

@Override
public void allocateGroup(ActorGroup group, Range<Integer> iterations, List<Core> cores, Configuration config) {
    int id = group.id();
    int numCores = config.getParameter("Group" + id + "CoreCount", Configuration.IntParameter.class).getValue();
    Configuration.PermutationParameter<Integer> coreOrderParam = config.getParameter("Group" + id + "CoreOrder",
            Configuration.PermutationParameter.class, Integer.class);
    ImmutableList<? extends Integer> coreOrder = coreOrderParam.getUniverse();

    List<Core> subset = new ArrayList<Core>(numCores);
    for (int i = 0; i < coreOrder.size() && subset.size() < numCores; ++i)
        if (coreOrder.get(i) < cores.size())
            subset.add(cores.get(coreOrder.get(i)));
    //We pass a null config to ensure it doesn't depend on the config.
    new FullDataParallelAllocationStrategy(numCores).allocateGroup(group, iterations, cores, null);
}

From source file:com.facebook.buck.rules.args.WorkerMacroArg.java

public WorkerMacroArg(MacroHandler macroHandler, BuildTarget target, CellPathResolver cellNames,
        BuildRuleResolver resolver, String unexpanded) throws MacroException {
    super(macroHandler, target, cellNames, resolver, unexpanded);
    for (MacroMatchResult matchResult : macroHandler.getMacroMatchResults(unexpanded)) {
        if (macroHandler.getExpander(matchResult.getMacroType()) instanceof WorkerMacroExpander
                && matchResult.getStartIndex() != 0) {
            throw new MacroException(
                    String.format("the worker macro in \"%s\" must be at the beginning", unexpanded));
        }// w w  w  . j ava  2  s . c  o m
    }

    // extract the BuildTargets referenced in any macros
    ImmutableList<BuildTarget> targets = macroHandler.extractParseTimeDeps(target, cellNames, unexpanded);

    if (targets.size() < 1) {
        throw new MacroException(String.format(
                "Unable to extract any build targets for the macros " + "used in \"%s\" of target %s",
                unexpanded, target));
    }
    this.buildTarget = targets.get(0);
    BuildRule workerTool = resolver.getRule(buildTarget);
    if (!(workerTool instanceof WorkerTool)) {
        throw new MacroException(String.format(
                "%s used in worker macro, \"%s\", of target %s does " + "not correspond to a worker_tool",
                buildTarget, unexpanded, target));
    }
    this.workerTool = (WorkerTool) workerTool;
    SourcePathResolver pathResolver = new SourcePathResolver(new SourcePathRuleFinder(resolver));
    Tool exe = this.workerTool.getTool();
    startupCommand = exe.getCommandPrefix(pathResolver);
    startupEnvironment = exe.getEnvironment();
    jobArgs = macroHandler.expand(target, cellNames, resolver, unexpanded).trim();
}

From source file:de.metanome.backend.input.csv.FileIterator.java

protected void failDifferingLine(ImmutableList<String> currentLine) throws InputIterationException {
    if (currentLine.size() != this.numberOfColumns()) {
        throw new InputIterationException("Csv line length did not match on line " + currentLineNumber);
    }/*from  www.  j a  v a  2 s.  co  m*/
}

From source file:com.facebook.buck.features.go.GoDescriptors.java

static GoBinary createGoBinaryRule(BuildTarget buildTarget, ProjectFilesystem projectFilesystem,
        BuildRuleParams params, ActionGraphBuilder graphBuilder, GoBuckConfig goBuckConfig,
        Linker.LinkableDepType linkStyle, Optional<GoLinkStep.LinkMode> linkMode, ImmutableSet<SourcePath> srcs,
        ImmutableSortedSet<SourcePath> resources, List<String> compilerFlags, List<String> assemblerFlags,
        List<String> linkerFlags, List<String> externalLinkerFlags, GoPlatform platform) {

    ImmutableList.Builder<BuildRule> extraDeps = ImmutableList.builder();

    GoCompile library = GoDescriptors.createGoCompileRule(
            buildTarget.withAppendedFlavors(InternalFlavor.of("compile"), platform.getFlavor()),
            projectFilesystem, params, graphBuilder, goBuckConfig, Paths.get("main"), srcs, compilerFlags,
            assemblerFlags, platform,/*from  w ww  .  ja v  a 2  s. co  m*/
            params.getDeclaredDeps().get().stream().map(BuildRule::getBuildTarget)
                    .collect(ImmutableList.toImmutableList()),
            ImmutableList.of(), Collections.singletonList(ListType.GoFiles));
    graphBuilder.addToIndex(library);
    extraDeps.add(library);

    SourcePathRuleFinder ruleFinder = new SourcePathRuleFinder(graphBuilder);
    SourcePathResolver pathResolver = DefaultSourcePathResolver.from(ruleFinder);
    BuildTarget target = createTransitiveSymlinkTreeTarget(buildTarget);
    SymlinkTree symlinkTree = makeSymlinkTree(target, projectFilesystem, ruleFinder, pathResolver,
            requireTransitiveGoLinkables(
                    buildTarget, graphBuilder, platform, params.getDeclaredDeps().get().stream()
                            .map(BuildRule::getBuildTarget).collect(ImmutableList.toImmutableList()),
                    /* includeSelf */ false));
    graphBuilder.addToIndex(symlinkTree);
    extraDeps.add(symlinkTree);

    LOG.verbose("Symlink tree for linking of %s: %s", buildTarget, symlinkTree);

    // find all the CGoLibraries being in direct or non direct dependency to
    // declared deps
    Iterable<BuildRule> cgoLinkables = getCgoLinkableDeps(library.getBuildDeps());
    ImmutableSet.Builder<String> extraFlags = ImmutableSet.builder();

    if (linkStyle == Linker.LinkableDepType.SHARED) {
        // Create a symlink tree with for all shared libraries needed by this binary.
        SymlinkTree sharedLibraries = graphBuilder.addToIndex(CxxDescriptionEnhancer
                .createSharedLibrarySymlinkTree(buildTarget, projectFilesystem, graphBuilder, ruleFinder,
                        platform.getCxxPlatform(), cgoLinkables, r -> Optional.empty()));
        extraDeps.add(sharedLibraries);

        // Embed a origin-relative library path into the binary so it can find the shared libraries.
        // The shared libraries root is absolute. Also need an absolute path to the linkOutput
        Path absBinaryDir = buildTarget.getCellPath()
                .resolve(BuildTargetPaths.getGenPath(projectFilesystem, buildTarget, "%s"));

        extraFlags.addAll(Linkers.iXlinker("-rpath",
                String.format("%s/%s", platform.getCxxPlatform().getLd().resolve(graphBuilder).origin(),
                        absBinaryDir.relativize(sharedLibraries.getRoot()).toString())));
    }

    ImmutableList<Arg> cxxLinkerArgs = getCxxLinkerArgs(graphBuilder, platform.getCxxPlatform(), cgoLinkables,
            linkStyle, StringArg.from(Iterables.concat(platform.getExternalLinkerFlags(), extraFlags.build(),
                    externalLinkerFlags)));

    // collect build rules from args (required otherwise referenced sources
    // won't build before linking)
    for (Arg arg : cxxLinkerArgs) {
        if (HasSourcePath.class.isInstance(arg)) {
            SourcePath pth = ((HasSourcePath) arg).getPath();
            extraDeps.addAll(ruleFinder.filterBuildRuleInputs(pth));
        }
    }

    if (!linkMode.isPresent()) {
        linkMode = Optional
                .of((cxxLinkerArgs.size() > 0) ? GoLinkStep.LinkMode.EXTERNAL : GoLinkStep.LinkMode.INTERNAL);
    }

    Linker cxxLinker = platform.getCxxPlatform().getLd().resolve(graphBuilder);
    return new GoBinary(buildTarget, projectFilesystem,
            params.withDeclaredDeps(ImmutableSortedSet.<BuildRule>naturalOrder()
                    .addAll(ruleFinder.filterBuildRuleInputs(symlinkTree.getLinks().values()))
                    .addAll(extraDeps.build()).addAll(BuildableSupport.getDepsCollection(cxxLinker, ruleFinder))
                    .build()).withoutExtraDeps(),
            resources, symlinkTree, library, platform.getLinker(), cxxLinker, linkMode.get(),
            ImmutableList.copyOf(linkerFlags), cxxLinkerArgs, platform);
}

From source file:com.google.cloud.firestore.BasePath.java

/**
 * Checks to see if this path is a prefix of (or equals) another path.
 *
 * @param path the path to check against
 * @return true if current path is a prefix of the other path.
 *///from w  w  w  .java 2 s .  co m
boolean isPrefixOf(BasePath<B> path) {
    ImmutableList<String> prefixSegments = getSegments();
    ImmutableList<String> childSegments = path.getSegments();
    if (prefixSegments.size() > path.getSegments().size()) {
        return false;
    }
    for (int i = 0; i < prefixSegments.size(); i++) {
        if (!prefixSegments.get(i).equals(childSegments.get(i))) {
            return false;
        }
    }
    return true;
}

From source file:org.geogit.api.plumbing.merge.MergeFeaturesOp.java

private Feature merge(RevFeature featureA, RevFeature featureB, RevFeature ancestor,
        RevFeatureType featureType) {//from   w w w  .  j a v a  2s .  c o  m

    SimpleFeatureBuilder featureBuilder = new SimpleFeatureBuilder((SimpleFeatureType) featureType.type());
    ImmutableList<Optional<Object>> valuesA = featureA.getValues();
    ImmutableList<Optional<Object>> valuesB = featureB.getValues();
    ImmutableList<Optional<Object>> valuesAncestor = ancestor.getValues();
    ImmutableList<PropertyDescriptor> descriptors = featureType.sortedDescriptors();
    for (int i = 0; i < descriptors.size(); i++) {
        Name name = descriptors.get(i).getName();
        Optional<Object> valueAncestor = valuesAncestor.get(i);
        Optional<Object> valueA = valuesA.get(i);
        if (!valueA.equals(valueAncestor)) {
            featureBuilder.set(name, valueA.orNull());
        } else {
            Optional<Object> valueB = valuesB.get(i);
            if (!valueB.equals(valueAncestor)) {
                featureBuilder.set(name, valueB.orNull());
            } else {
                featureBuilder.set(name, valueAncestor.orNull());
            }
        }
    }
    return featureBuilder.buildFeature(nodeRefA.name());

}

From source file:com.google.template.soy.jbcsrc.restricted.BytecodeUtils.java

private static Expression asArray(final Type arrayType, final ImmutableList<? extends Expression> elements) {
    final Type elementType = arrayType.getElementType();
    return new Expression(arrayType, Feature.NON_NULLABLE) {
        @Override/*from  w w  w.  j ava  2 s. com*/
        protected void doGen(CodeBuilder adapter) {
            adapter.pushInt(elements.size());
            adapter.newArray(elementType);
            for (int i = 0; i < elements.size(); i++) {
                adapter.dup(); // dup the array
                adapter.pushInt(i); // the index to store into
                elements.get(i).gen(adapter); // the element to store
                adapter.arrayStore(elementType);
            }
        }
    };
}

From source file:com.proofpoint.event.collector.queue.FileBackedQueue.java

@Override
public List<T> dequeue(int numItems) throws IOException {
    checkArgument(numItems > 0, "numItems must be greater than zero");

    Builder<T> builder = new Builder<>();
    int chunks = 0;
    while (chunks < numItems) {
        byte[] item = queue.dequeue();
        if (item == null) {
            break;
        }//from   ww w.jav a  2  s.co m
        builder.add(codec.fromJson(item));
        chunks++;
    }

    ImmutableList<T> items = builder.build();
    itemsDequeued.getAndAdd(items.size());
    return items;
}