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.eigenbase.rex.RexUtil.java

/**
 * Converts a collection of expressions into an OR.
 * If there are zero expressions, returns FALSE.
 * If there is one expression, returns just that expression.
 * Removes expressions that always evaluate to FALSE.
 * Flattens expressions that are ORs./*  w ww  .  j a  va  2s. com*/
 */
public static RexNode composeDisjunction(RexBuilder rexBuilder, Iterable<? extends RexNode> nodes,
        boolean nullOnEmpty) {
    ImmutableList<RexNode> list = flattenOr(nodes);
    switch (list.size()) {
    case 0:
        return nullOnEmpty ? null : rexBuilder.makeLiteral(false);
    case 1:
        return list.get(0);
    default:
        return rexBuilder.makeCall(SqlStdOperatorTable.OR, list);
    }
}

From source file:org.eigenbase.rex.RexUtil.java

/**
 * Converts a collection of expressions into an AND.
 * If there are zero expressions, returns TRUE.
 * If there is one expression, returns just that expression.
 * Removes expressions that always evaluate to TRUE.
 * Returns null only if {@code nullOnEmpty} and expression is TRUE.
 *///from  w w w . j  av  a2 s .  co  m
public static RexNode composeConjunction(RexBuilder rexBuilder, Iterable<? extends RexNode> nodes,
        boolean nullOnEmpty) {
    ImmutableList<RexNode> list = flattenAnd(nodes);
    switch (list.size()) {
    case 0:
        return nullOnEmpty ? null : rexBuilder.makeLiteral(true);
    case 1:
        return list.get(0);
    default:
        return rexBuilder.makeCall(SqlStdOperatorTable.AND, list);
    }
}

From source file:paperparcel.PaperParcelValidator.java

ValidationReport<TypeElement> validate(TypeElement element, OptionsDescriptor options) {
    ValidationReport.Builder<TypeElement> builder = ValidationReport.about(element);

    if (element.getKind() != ElementKind.CLASS) {
        builder.addError(ErrorMessages.PAPERPARCEL_ON_NON_CLASS);
    }/*from   www .  j  a  v a  2s  .c  om*/
    if (element.getModifiers().contains(Modifier.ABSTRACT)) {
        builder.addError(ErrorMessages.PAPERPARCEL_ON_ABSTRACT_CLASS);
    }
    if (!Utils.isParcelable(elements, types, element.asType())) {
        builder.addError(ErrorMessages.PAPERPARCEL_ON_NON_PARCELABLE);
    }
    if (implementsAnnotation(elements, types, element)) {
        builder.addError(ErrorMessages.PAPERPARCEL_ON_ANNOTATION);
    }
    ElementKind enclosingKind = element.getEnclosingElement().getKind();
    if (enclosingKind.isClass() || enclosingKind.isInterface()) {
        if (Visibility.ofElement(element) == Visibility.PRIVATE) {
            builder.addError(ErrorMessages.PAPERPARCEL_ON_PRIVATE_CLASS);
        }
        if (!element.getModifiers().contains(Modifier.STATIC)) {
            builder.addError(ErrorMessages.PAPERPARCEL_ON_NON_STATIC_INNER_CLASS);
        }
    }

    if (options.excludeNonExposedFields() && options.exposeAnnotationNames().isEmpty()) {
        builder.addError(ErrorMessages.NO_EXPOSE_ANNOTATIONS_DEFINED, element, options.mirror());
    }

    if (!Utils.isSingleton(types, element)) {
        ImmutableList<ExecutableElement> constructors = Utils.orderedConstructorsIn(element,
                options.reflectAnnotations());
        if (constructors.size() == 0) {
            builder.addError(ErrorMessages.PAPERPARCEL_NO_VISIBLE_CONSTRUCTOR);
        }

        boolean kapt2 = KAPT2_TYPES.equals(types.getClass().getName());

        ImmutableList<VariableElement> fields = Utils.getFieldsToParcel(element, options);
        for (VariableElement field : fields) {
            String fieldName = field.getSimpleName().toString();
            if (Utils.containsWildcards(field.asType())) {
                builder.addError(ErrorMessages.WILDCARD_IN_FIELD_TYPE, field);
            } else if (Utils.isRawType(field.asType())) {
                builder.addError(ErrorMessages.FIELD_MISSING_TYPE_ARGUMENTS, field);
            } else if (Utils.hasRecursiveTypeParameter(field.asType())) {
                builder.addError(ErrorMessages.FIELD_TYPE_IS_RECURSIVE, field);
            } else if (Utils.containsIntersection(field.asType())) {
                builder.addError(ErrorMessages.FIELD_TYPE_IS_INTERSECTION_TYPE, field);
            }
            if (kapt2 && SourceVersion.isKeyword(fieldName)) {
                // This is due to a subtle bug in kapt2 with java keywords as variable. The constructor
                // arguments end up being named differently than the field itself (e.g. "p"), meaning
                // PaperParcel can no longer pair them to the associated fields. The issue is resolved
                // in kapt3, so this error message just asks the user to update their kotlin version.
                builder.addError(String.format(ErrorMessages.KAPT2_INVALID_FIELD_NAME, fieldName), field);
            }
        }
    }

    return builder.build();
}

From source file:com.google.javascript.jscomp.testing.ScopeSubject.java

public DeclarationSubject declares(String name) {
    AbstractVar<?, ?> var = getVar(name);
    if (var == null) {
        ImmutableList<AbstractVar<?, ?>> declared = ImmutableList.copyOf(actual.getAllAccessibleVariables());
        ImmutableList<String> names = declared.stream().map(AbstractVar::getName).collect(toImmutableList());
        if (names.size() > 10) {
            names = ImmutableList.<String>builder().addAll(names.subList(0, 9))
                    .add("and " + (names.size() - 9) + " others").build();
        }/*from w w w.  jav a2 s  . com*/
        failWithoutActual(fact("expected to declare", name), simpleFact("but did not"),
                fact("did declare", Joiner.on(", ").join(names)), fact("scope was", actual));
    }
    return new DeclarationSubject(var);
}

From source file:com.google.devtools.build.lib.packages.SkylarkProvider.java

@Override
protected Info createInstanceFromSkylark(Object[] args, Location loc) throws EvalException {
    if (signature.getSignature().getShape().hasKwArg()) {
        @SuppressWarnings("unchecked")
        Map<String, Object> kwargs = (Map<String, Object>) args[0];
        return new SkylarkInfo(this, kwargs, loc);
    } else {/* www.j  a  v  a  2  s.  c o  m*/
        // todo(dslomov): implement shape sharing.
        ImmutableList<String> names = signature.getSignature().getNames();
        Preconditions.checkState(names.size() == args.length);
        ImmutableMap.Builder<String, Object> fields = ImmutableMap.builder();
        for (int i = 0; i < args.length; i++) {
            if (args[i] != null) {
                fields.put(names.get(i), args[i]);
            }
        }
        return new SkylarkInfo(this, fields.build(), loc);
    }
}

From source file:google.registry.rdap.RdapNameserverSearchAction.java

/** Output JSON for a list of hosts. */
private RdapSearchResults makeSearchResults(List<HostResource> hosts, DateTime now) {
    OutputDataType outputDataType = (hosts.size() > 1) ? OutputDataType.SUMMARY : OutputDataType.FULL;
    ImmutableList.Builder<ImmutableMap<String, Object>> jsonListBuilder = new ImmutableList.Builder<>();
    for (HostResource host : Iterables.limit(hosts, rdapResultSetMaxSize)) {
        jsonListBuilder.add(rdapJsonFormatter.makeRdapJsonForHost(host, false, rdapLinkBase, rdapWhoisServer,
                now, outputDataType));//ww w .  java  2  s. c  o  m
    }
    ImmutableList<ImmutableMap<String, Object>> jsonList = jsonListBuilder.build();
    return RdapSearchResults.create(jsonList, jsonList.size() < hosts.size());
}

From source file:com.facebook.buck.core.resources.AbstractResourcesConfig.java

@Value.Lazy
public ImmutableMap<String, ResourceAmounts> getResourceAmountsPerRuleType() {
    ImmutableMap.Builder<String, ResourceAmounts> result = ImmutableMap.builder();
    ImmutableMap<String, String> entries = getDelegate()
            .getEntriesForSection(RESOURCES_PER_RULE_SECTION_HEADER);
    for (String ruleName : entries.keySet()) {
        ImmutableList<String> configAmounts = getDelegate()
                .getListWithoutComments(RESOURCES_PER_RULE_SECTION_HEADER, ruleName);
        Preconditions.checkArgument(configAmounts.size() == ResourceAmounts.RESOURCE_TYPE_COUNT,
                "Buck config entry [%s].%s contains %s values, but expected to contain %s values "
                        + "in the following order: cpu, memory, disk_io, network_io",
                RESOURCES_PER_RULE_SECTION_HEADER, ruleName, configAmounts.size(),
                ResourceAmounts.RESOURCE_TYPE_COUNT);
        ResourceAmounts amounts = ResourceAmounts.of(Integer.parseInt(configAmounts.get(0)),
                Integer.parseInt(configAmounts.get(1)), Integer.parseInt(configAmounts.get(2)),
                Integer.parseInt(configAmounts.get(3)));
        result.put(ruleName, amounts);//from w ww  . j a v  a2  s  .co  m
    }
    return result.build();
}

From source file:com.opengamma.strata.pricer.curve.SyntheticCurveCalibrator.java

/**
 * Constructs the synthetic market data from an existing rates provider and the configuration of the new curves.
 * //from w  ww . j a  v  a2  s.  co m
 * @param group  the curve group definition for the synthetic curves and instruments
 * @param inputProvider  the input rates provider
 * @param refData  the reference data, used to resolve the trades
 * @return the market data
 */
MarketData marketData(CurveGroupDefinition group, RatesProvider inputProvider, ReferenceData refData) {

    // Retrieve the set of required indices and the list of required currencies
    Set<Index> indicesRequired = new HashSet<Index>();
    List<Currency> ccyRequired = new ArrayList<>();
    for (CurveGroupEntry entry : group.getEntries()) {
        indicesRequired.addAll(entry.getIndices());
        ccyRequired.addAll(entry.getDiscountCurrencies());
    }
    // Retrieve the required time series if present in the original provider
    Map<IndexQuoteId, LocalDateDoubleTimeSeries> ts = new HashMap<>();
    for (Index idx : indicesRequired) {
        ts.put(IndexQuoteId.of(idx), inputProvider.timeSeries(idx));
    }

    LocalDate valuationDate = inputProvider.getValuationDate();
    ImmutableList<NodalCurveDefinition> curveGroups = group.getCurveDefinitions();
    // Create fake market quotes of 0, only to be able to generate trades
    Map<MarketDataId<?>, Double> mapId0 = new HashMap<>();
    for (NodalCurveDefinition entry : curveGroups) {
        ImmutableList<CurveNode> nodes = entry.getNodes();
        for (int i = 0; i < nodes.size(); i++) {
            for (MarketDataId<?> key : nodes.get(i).requirements()) {
                mapId0.put(key, 0.0d);
            }
        }
    }
    ImmutableMarketData marketQuotes0 = ImmutableMarketData.of(valuationDate, mapId0);
    // Generate market quotes from the trades
    Map<MarketDataId<?>, Object> mapIdSy = new HashMap<>();
    for (NodalCurveDefinition entry : curveGroups) {
        ImmutableList<CurveNode> nodes = entry.getNodes();
        for (CurveNode node : nodes) {
            ResolvedTrade trade = node.resolvedTrade(1d, marketQuotes0, refData);
            double mq = measures.value(trade, inputProvider);
            MarketDataId<?> k = node.requirements().iterator().next();
            mapIdSy.put(k, mq);
        }
    }
    // Generate quotes for FX pairs. The first currency is arbitrarily selected as starting point. 
    // The crosses are automatically generated by the MarketDataFxRateProvider used in calibration.
    for (int loopccy = 1; loopccy < ccyRequired.size(); loopccy++) {
        CurrencyPair ccyPair = CurrencyPair.of(ccyRequired.get(0), ccyRequired.get(loopccy));
        FxRateId fxId = FxRateId.of(ccyPair);
        mapIdSy.put(fxId, FxRate.of(ccyPair, inputProvider.fxRate(ccyPair)));
    }
    return MarketData.of(valuationDate, mapIdSy, ts);
}

From source file:com.google.api.tools.framework.aspects.authentication.AuthConfigAspect.java

@Override
public String getDocumentation(ProtoElement element) {
    ImmutableList<String> scopes = getOauthScopes(element);
    return scopes.isEmpty() ? null : snippet.authDocumentation(scopes, scopes.size() == 1).prettyPrint();
}

From source file:com.google.devtools.build.lib.bazel.coverage.CoverageReportActionBuilder.java

private FileWriteAction generateLcovFileWriteAction(Artifact lcovArtifact,
        ImmutableList<Artifact> coverageArtifacts) {
    List<String> filepaths = new ArrayList<>(coverageArtifacts.size());
    for (Artifact artifact : coverageArtifacts) {
        filepaths.add(artifact.getExecPathString());
    }//from   w w w . ja  v a2 s.c  o m
    return FileWriteAction.create(ACTION_OWNER, lcovArtifact, Joiner.on('\n').join(filepaths),
            /*makeExecutable=*/ false, FileWriteAction.Compression.DISALLOW);
}