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:eu.eidas.auth.commons.attribute.AttributeRegistry.java

@Nonnull
public ImmutableSortedSet<AttributeDefinition<?>> getAttributes() {
    try {/*ww w.j a  va 2s  . c  o  m*/
        ImmutableList<? extends SingletonAccessor<ImmutableSortedSet<AttributeDefinition<?>>>> accessors = getAccessors();
        if (accessors.size() == 1) {
            return accessors.get(0).get();
        }
        return getByFilter(ALL_FILTER);
    } catch (IOException ioe) {
        throw new InternalErrorEIDASException(EidasErrorKey.INTERNAL_ERROR.errorCode(), ioe.getMessage(), ioe);
    }
}

From source file:org.locationtech.geogig.osm.internal.CreateOSMChangesetOp.java

/**
 * Executes the diff operation.//from  w  w w .  j av  a2 s  . co m
 * 
 * @return an iterator to a set of differences between the two trees
 * @see DiffEntry
 */
@Override
protected Iterator<ChangeContainer> _call() {

    Iterator<DiffEntry> nodeIterator = command(DiffOp.class).setFilter(OSMUtils.NODE_TYPE_NAME)
            .setNewVersion(newRefSpec).setOldVersion(oldRefSpec).setReportTrees(false).call();
    Iterator<DiffEntry> wayIterator = command(DiffOp.class).setFilter(OSMUtils.WAY_TYPE_NAME)
            .setNewVersion(newRefSpec).setOldVersion(oldRefSpec).setReportTrees(false).call();
    Iterator<DiffEntry> iterator = Iterators.concat(nodeIterator, wayIterator);

    final EntityConverter converter = new EntityConverter();
    Function<DiffEntry, ChangeContainer> function = new Function<DiffEntry, ChangeContainer>() {

        @Override
        @Nullable
        public ChangeContainer apply(@Nullable DiffEntry diff) {
            NodeRef ref = diff.changeType().equals(ChangeType.REMOVED) ? diff.getOldObject()
                    : diff.getNewObject();
            RevFeature revFeature = command(RevObjectParse.class).setObjectId(ref.objectId())
                    .call(RevFeature.class).get();
            RevFeatureType revFeatureType = command(RevObjectParse.class).setObjectId(ref.getMetadataId())
                    .call(RevFeatureType.class).get();
            SimpleFeatureBuilder featureBuilder = new SimpleFeatureBuilder(
                    (SimpleFeatureType) revFeatureType.type());
            ImmutableList<PropertyDescriptor> descriptors = revFeatureType.sortedDescriptors();
            ImmutableList<Optional<Object>> values = revFeature.getValues();
            for (int i = 0; i < descriptors.size(); i++) {
                PropertyDescriptor descriptor = descriptors.get(i);
                Optional<Object> value = values.get(i);
                featureBuilder.set(descriptor.getName(), value.orNull());
            }
            SimpleFeature feature = featureBuilder.buildFeature(ref.name());
            Entity entity = converter.toEntity(feature, id);
            EntityContainer container;
            if (entity instanceof Node) {
                container = new NodeContainer((Node) entity);
            } else {
                container = new WayContainer((Way) entity);
            }

            ChangeAction action = diff.changeType().equals(ChangeType.ADDED) ? ChangeAction.Create
                    : diff.changeType().equals(ChangeType.MODIFIED) ? ChangeAction.Modify : ChangeAction.Delete;

            return new ChangeContainer(container, action);

        }

    };
    return Iterators.transform(iterator, function);
}

From source file:com.google.api.server.spi.dispatcher.PathTrie.java

private Result<T> resolve(HttpMethod method, List<String> pathSegments, int index, List<String> rawParameters) {
    if (index < pathSegments.size()) {
        String segment = pathSegments.get(index);
        PathTrie<T> subTrie = subTries.get(segment);
        if (subTrie != null) {
            Result<T> result = subTrie.resolve(method, pathSegments, index + 1, rawParameters);
            if (result != null) {
                return result;
            }/*from   w w  w. j a va2 s  . c  om*/
        }
        subTrie = subTries.get(PARAMETER_PATH_SEGMENT);
        if (subTrie != null) {
            // TODO: We likely need to enforce non-empty values here.
            rawParameters.add(segment);
            Result<T> result = subTrie.resolve(method, pathSegments, index + 1, rawParameters);
            if (result == null) {
                rawParameters.remove(rawParameters.size() - 1);
            }
            return result;
        }
        return null;
    } else if (httpMethodMap.containsKey(method)) {
        MethodInfo<T> methodInfo = httpMethodMap.get(method);
        ImmutableList<String> parameterNames = methodInfo.parameterNames;
        Preconditions.checkState(rawParameters.size() == parameterNames.size());
        Map<String, String> rawParameterMap = Maps.newHashMap();
        for (int i = 0; i < parameterNames.size(); i++) {
            rawParameterMap.put(parameterNames.get(i), decodeUri(rawParameters.get(i)));
        }
        return new Result<>(methodInfo.value, rawParameterMap);
    }
    return null;
}

From source file:dagger.internal.codegen.DependencyCycleValidator.java

/**
 * Reports a dependency cycle at the dependency into the cycle that is closest to an entry point.
 *
 * <p>Looks for the shortest path from the component that contains the cycle (all bindings in a
 * cycle must be in the same component; see below) to some binding in the cycle. Then looks for
 * the last dependency in that path that is not in the cycle; that is the dependency that will be
 * reported, so that the dependency trace will end just before the cycle.
 *
 * <p>Proof (by counterexample) that all bindings in a cycle must be in the same component: Assume
 * one binding in the cycle is in a parent component. Bindings cannot depend on bindings in child
 * components, so that binding cannot depend on the next binding in the cycle.
 *///  w w  w .  j a  v  a2  s . c  o m
private void reportCycle(Cycle<Node> cycle, BindingGraph bindingGraph, DiagnosticReporter diagnosticReporter) {
    ImmutableList<Node> path = shortestPathToCycleFromAnEntryPoint(cycle, bindingGraph);
    Node cycleStartNode = path.get(path.size() - 1);
    Node previousNode = path.get(path.size() - 2);
    DependencyEdge dependencyToReport = chooseDependencyEdgeConnecting(previousNode, cycleStartNode,
            bindingGraph);
    diagnosticReporter.reportDependency(ERROR, dependencyToReport,
            errorMessage(cycle.shift(cycleStartNode), bindingGraph));
}

From source file:com.google.template.soy.jssrc.internal.JsSrcMain.java

/**
 * Generates JS source files given a Soy parse tree, an options object, an optional bundle of
 * translated messages, and information on where to put the output files.
 *
 * @param soyTree The Soy parse tree to generate JS source code for.
 * @param jsSrcOptions The compilation options relevant to this backend.
 * @param locale The current locale that we're generating JS for, or null if not applicable.
 * @param msgBundle The bundle of translated messages, or null to use the messages from the Soy
 *     source.//w ww  .  j  a v  a  2  s  .  c o m
 * @param outputPathFormat The format string defining how to build the output file path
 *     corresponding to an input file path.
 * @param inputPathsPrefix The input path prefix, or empty string if none.
 * @throws SoySyntaxException If a syntax error is found.
 * @throws IOException If there is an error in opening/writing an output JS file.
 */
public void genJsFiles(SoyFileSetNode soyTree, SoyJsSrcOptions jsSrcOptions, @Nullable String locale,
        @Nullable SoyMsgBundle msgBundle, String outputPathFormat, String inputPathsPrefix)
        throws SoySyntaxException, IOException {

    List<String> jsFileContents = genJsSrc(soyTree, jsSrcOptions, msgBundle);

    ImmutableList<SoyFileNode> srcsToCompile = ImmutableList
            .copyOf(Iterables.filter(soyTree.getChildren(), SoyFileNode.MATCH_SRC_FILENODE));

    if (srcsToCompile.size() != jsFileContents.size()) {
        throw new AssertionError(String.format("Expected to generate %d code chunk(s), got %d",
                srcsToCompile.size(), jsFileContents.size()));
    }

    Multimap<String, Integer> outputs = MainEntryPointUtils.mapOutputsToSrcs(locale, outputPathFormat,
            inputPathsPrefix, srcsToCompile);

    for (String outputFilePath : outputs.keySet()) {
        Writer out = Files.newWriter(new File(outputFilePath), UTF_8);
        try {
            boolean isFirst = true;
            for (int inputFileIndex : outputs.get(outputFilePath)) {
                if (isFirst) {
                    isFirst = false;
                } else {
                    // Concatenating JS files is not safe unless we know that the last statement from one
                    // couldn't combine with the isFirst statement of the next.  Inserting a semicolon will
                    // prevent this from happening.
                    out.write("\n;\n");
                }
                out.write(jsFileContents.get(inputFileIndex));
            }
        } finally {
            out.close();
        }
    }
}

From source file:com.facebook.presto.cli.AlignedTablePrinter.java

@Override
public void printRows(List<List<?>> rows, boolean complete) throws IOException {
    rowCount += rows.size();/*from  ww  w .ja  v a  2 s. c o  m*/
    int columns = fieldNames.size();

    int[] maxWidth = new int[columns];
    for (int i = 0; i < columns; i++) {
        maxWidth[i] = max(1, consoleWidth(fieldNames.get(i)));
    }
    for (List<?> row : rows) {
        for (int i = 0; i < row.size(); i++) {
            String s = formatValue(row.get(i));
            maxWidth[i] = max(maxWidth[i], maxLineLength(s));
        }
    }

    if (!headerOutput) {
        headerOutput = true;

        for (int i = 0; i < columns; i++) {
            if (i > 0) {
                writer.append('|');
            }
            String name = fieldNames.get(i);
            writer.append(center(name, maxWidth[i], 1));
        }
        writer.append('\n');

        for (int i = 0; i < columns; i++) {
            if (i > 0) {
                writer.append('+');
            }
            writer.append(repeat("-", maxWidth[i] + 2));
        }
        writer.append('\n');
    }

    for (List<?> row : rows) {
        List<List<String>> columnLines = new ArrayList<>(columns);
        int maxLines = 1;
        for (int i = 0; i < columns; i++) {
            String s = formatValue(row.get(i));
            ImmutableList<String> lines = ImmutableList.copyOf(LINE_SPLITTER.split(s));
            columnLines.add(lines);
            maxLines = max(maxLines, lines.size());
        }

        for (int line = 0; line < maxLines; line++) {
            for (int column = 0; column < columns; column++) {
                if (column > 0) {
                    writer.append('|');
                }
                List<String> lines = columnLines.get(column);
                String s = (line < lines.size()) ? lines.get(line) : "";
                boolean numeric = row.get(column) instanceof Number;
                String out = align(s, maxWidth[column], 1, numeric);
                if ((!complete || (rowCount > 1)) && ((line + 1) < lines.size())) {
                    out = out.substring(0, out.length() - 1) + "+";
                }
                writer.append(out);
            }
            writer.append('\n');
        }
    }

    writer.flush();
}

From source file:com.google.devtools.build.lib.skyframe.PackageFunction.java

/**
 * Fetch the skylark loads for this BUILD file. If any of them haven't been computed yet,
 * returns null.//ww w .j  a v a  2  s.  com
 */
@Nullable
static SkylarkImportResult fetchImportsFromBuildFile(Path buildFilePath, PackageIdentifier packageId,
        BuildFileAST buildFileAST, Environment env,
        SkylarkImportLookupFunction skylarkImportLookupFunctionForInlining)
        throws PackageFunctionException, InterruptedException {
    Preconditions.checkArgument(!packageId.getRepository().isDefault());

    ImmutableList<SkylarkImport> imports = buildFileAST.getImports();
    Map<String, Extension> importMap = Maps.newHashMapWithExpectedSize(imports.size());
    ImmutableList.Builder<SkylarkFileDependency> fileDependencies = ImmutableList.builder();
    ImmutableMap<String, Label> importPathMap;

    // Find the labels corresponding to the load statements.
    Label labelForCurrBuildFile;
    try {
        labelForCurrBuildFile = Label.create(packageId, "BUILD");
    } catch (LabelSyntaxException e) {
        // Shouldn't happen; the Label is well-formed by construction.
        throw new IllegalStateException(e);
    }
    try {
        importPathMap = SkylarkImportLookupFunction.findLabelsForLoadStatements(imports, labelForCurrBuildFile,
                env);
        if (importPathMap == null) {
            return null;
        }
    } catch (SkylarkImportFailedException e) {
        throw new PackageFunctionException(new BuildFileContainsErrorsException(packageId, e.getMessage()),
                Transience.PERSISTENT);
    }

    // Look up and load the imports.
    ImmutableCollection<Label> importLabels = importPathMap.values();
    List<SkyKey> importLookupKeys = Lists.newArrayListWithExpectedSize(importLabels.size());
    boolean inWorkspace = buildFilePath.getBaseName().endsWith("WORKSPACE");
    for (Label importLabel : importLabels) {
        importLookupKeys.add(SkylarkImportLookupValue.key(importLabel, inWorkspace));
    }
    Map<SkyKey, SkyValue> skylarkImportMap = Maps.newHashMapWithExpectedSize(importPathMap.size());
    boolean valuesMissing = false;

    try {
        if (skylarkImportLookupFunctionForInlining == null) {
            // Not inlining
            Map<SkyKey, ValueOrException2<SkylarkImportFailedException, InconsistentFilesystemException>> skylarkLookupResults = env
                    .getValuesOrThrow(importLookupKeys, SkylarkImportFailedException.class,
                            InconsistentFilesystemException.class);
            valuesMissing = env.valuesMissing();
            for (Map.Entry<SkyKey, ValueOrException2<SkylarkImportFailedException, InconsistentFilesystemException>> entry : skylarkLookupResults
                    .entrySet()) {
                // Fetching the value will raise any deferred exceptions
                skylarkImportMap.put(entry.getKey(), entry.getValue().get());
            }
        } else {
            // Inlining calls to SkylarkImportLookupFunction
            LinkedHashMap<Label, SkylarkImportLookupValue> alreadyVisitedImports = Maps
                    .newLinkedHashMapWithExpectedSize(importLookupKeys.size());
            for (SkyKey importLookupKey : importLookupKeys) {
                SkyValue skyValue = skylarkImportLookupFunctionForInlining
                        .computeWithInlineCalls(importLookupKey, env, alreadyVisitedImports);
                if (skyValue == null) {
                    Preconditions.checkState(env.valuesMissing(), "no skylark import value for %s",
                            importLookupKey);
                    // We continue making inline calls even if some requested values are missing, to
                    // maximize the number of dependent (non-inlined) SkyFunctions that are requested, thus
                    // avoiding a quadratic number of restarts.
                    valuesMissing = true;
                } else {
                    skylarkImportMap.put(importLookupKey, skyValue);
                }
            }

        }
    } catch (SkylarkImportFailedException e) {
        throw new PackageFunctionException(new BuildFileContainsErrorsException(packageId, e.getMessage()),
                Transience.PERSISTENT);
    } catch (InconsistentFilesystemException e) {
        throw new PackageFunctionException(new NoSuchPackageException(packageId, e.getMessage(), e),
                Transience.PERSISTENT);
    }

    if (valuesMissing) {
        // Some imports are unavailable.
        return null;
    }

    // Process the loaded imports.
    for (Entry<String, Label> importEntry : importPathMap.entrySet()) {
        String importString = importEntry.getKey();
        Label importLabel = importEntry.getValue();
        SkyKey keyForLabel = SkylarkImportLookupValue.key(importLabel, inWorkspace);
        SkylarkImportLookupValue importLookupValue = (SkylarkImportLookupValue) skylarkImportMap
                .get(keyForLabel);
        importMap.put(importString, importLookupValue.getEnvironmentExtension());
        fileDependencies.add(importLookupValue.getDependency());
    }

    return new SkylarkImportResult(importMap, transitiveClosureOfLabels(fileDependencies.build()));
}

From source file:org.apache.calcite.plan.RelOptRuleOperand.java

/** Private constructor.
 *
 * <p>Do not call from outside package, and do not create a sub-class.
 *
 * <p>The other constructor is deprecated; when it is removed, make fields
 * {@link #parent}, {@link #ordinalInParent} and {@link #solveOrder} final,
 * and add constructor parameters for them. See
 * <a href="https://issues.apache.org/jira/browse/CALCITE-1166">[CALCITE-1166]
 * Disallow sub-classes of RelOptRuleOperand</a>. */
<R extends RelNode> RelOptRuleOperand(Class<R> clazz, RelTrait trait, Predicate<? super R> predicate,
        RelOptRuleOperandChildPolicy childPolicy, ImmutableList<RelOptRuleOperand> children) {
    assert clazz != null;
    switch (childPolicy) {
    case ANY:// w w w  . ja v a  2 s  . c  o  m
        break;
    case LEAF:
        assert children.size() == 0;
        break;
    case UNORDERED:
        assert children.size() == 1;
        break;
    default:
        assert children.size() > 0;
    }
    this.childPolicy = childPolicy;
    this.clazz = Preconditions.checkNotNull(clazz);
    this.trait = trait;
    //noinspection unchecked
    this.predicate = Preconditions.checkNotNull((Predicate) predicate);
    this.children = children;
    for (RelOptRuleOperand child : this.children) {
        assert child.parent == null : "cannot re-use operands";
        child.parent = this;
    }
}

From source file:com.google.devtools.build.lib.syntax.Eval.java

private void execStatements(ImmutableList<Statement> statements) throws EvalException, InterruptedException {
    // Hot code path, good chance of short lists which don't justify the iterator overhead.
    for (int i = 0; i < statements.size(); i++) {
        exec(statements.get(i));/* w w  w .  j av  a  2s. com*/
    }
}

From source file:org.eigenbase.sql.type.CompositeOperandTypeChecker.java

/**
 * Package private. Use {@link OperandTypes#and},
 * {@link OperandTypes#or}.// w w  w.  j a  v a  2 s .co  m
 */
CompositeOperandTypeChecker(Composition composition, ImmutableList<SqlSingleOperandTypeChecker> allowedRules) {
    assert null != allowedRules;
    assert allowedRules.size() > 1;
    this.allowedRules = allowedRules;
    this.composition = composition;
}