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:com.google.javascript.jscomp.parsing.TypeDeclarationsIRFactory.java

/**
 * The root of a JSTypeExpression is very different from an AST node, even
 * though we use the same Java class to represent them.
 * This function converts root nodes of JSTypeExpressions into TypeDeclaration ASTs,
 * to make them more similar to ordinary AST nodes.
 *
 * @return the root node of a TypeDeclaration AST, or null if no type is
 *         available for the node.//ww w.jav  a2s. c o m
 */
// TODO(dimvar): Eventually, we want to just parse types to the new
// representation directly, and delete this function.
@Nullable
public static TypeDeclarationNode convertTypeNodeAST(Node n) {
    int token = n.getType();
    switch (token) {
    case Token.STAR:
    case Token.EMPTY: // for function types that don't declare a return type
        return anyType();
    case Token.VOID:
        return undefinedType();
    case Token.BANG:
        // TODO(alexeagle): non-nullable is assumed to be the default
        return convertTypeNodeAST(n.getFirstChild());
    case Token.STRING:
        String typeName = n.getString();
        switch (typeName) {
        case "boolean":
            return booleanType();
        case "number":
            return numberType();
        case "string":
            return stringType();
        case "null":
        case "undefined":
        case "void":
            return null;
        default:
            TypeDeclarationNode root = namedType(typeName);
            if (n.getChildCount() > 0 && n.getFirstChild().isBlock()) {
                Node block = n.getFirstChild();
                if ("Array".equals(typeName)) {
                    return arrayType(convertTypeNodeAST(block.getFirstChild()));
                }
                return parameterizedType(root, Iterables.transform(block.children(), CONVERT_TYPE_NODE));
            }
            return root;
        }
    case Token.QMARK:
        Node child = n.getFirstChild();
        return child == null ? anyType()
                // For now, our ES6_TYPED language doesn't support nullable
                // so we drop it before building the tree.
                // : nullable(convertTypeNodeAST(child));
                : convertTypeNodeAST(child);
    case Token.LC:
        LinkedHashMap<String, TypeDeclarationNode> properties = new LinkedHashMap<>();
        for (Node field : n.getFirstChild().children()) {
            boolean isFieldTypeDeclared = field.getType() == Token.COLON;
            Node fieldNameNode = isFieldTypeDeclared ? field.getFirstChild() : field;
            String fieldName = fieldNameNode.getString();
            if (fieldName.startsWith("'") || fieldName.startsWith("\"")) {
                fieldName = fieldName.substring(1, fieldName.length() - 1);
            }
            TypeDeclarationNode fieldType = isFieldTypeDeclared ? convertTypeNodeAST(field.getLastChild())
                    : null;
            properties.put(fieldName, fieldType);
        }
        return recordType(properties);
    case Token.ELLIPSIS:
        return arrayType(convertTypeNodeAST(n.getFirstChild()));
    case Token.PIPE:
        ImmutableList<TypeDeclarationNode> types = FluentIterable.from(n.children())
                .transform(CONVERT_TYPE_NODE).filter(Predicates.notNull()).toList();
        switch (types.size()) {
        case 0:
            return null;
        case 1:
            return types.get(0);
        default:
            return unionType(types);
        }
    case Token.FUNCTION:
        Node returnType = anyType();
        LinkedHashMap<String, TypeDeclarationNode> parameters = new LinkedHashMap<>();
        String restName = null;
        TypeDeclarationNode restType = null;
        for (Node child2 : n.children()) {
            if (child2.isParamList()) {
                int paramIdx = 1;
                for (Node param : child2.children()) {
                    String paramName = "p" + paramIdx++;
                    if (param.getType() == Token.ELLIPSIS) {
                        restName = paramName;
                        if (param.getFirstChild() != null) {
                            restType = convertTypeNodeAST(param.getFirstChild());
                        }
                    } else {
                        parameters.put(paramName, convertTypeNodeAST(param));
                    }
                }
            } else if (child2.isNew()) {
                // TODO(alexeagle): keep the constructor signatures on the tree, and emit them following
                // the syntax in TypeScript 1.4 spec, section 3.7.8 Constructor Type Literals
            } else if (child2.isThis()) {
                // Not expressible in TypeScript syntax, so we omit them from the tree.
                // They could be added as properties on the result node.
            } else {
                returnType = convertTypeNodeAST(child2);
            }
        }
        return functionType(returnType, parameters, restName, restType);
    case Token.EQUALS:
        return optionalParameter(convertTypeNodeAST(n.getFirstChild()));
    default:
        throw new IllegalArgumentException(
                "Unsupported node type: " + Token.name(n.getType()) + " " + n.toStringTree());
    }
}

From source file:com.analog.lyric.collect.Supers.java

/**
 * Returns nearest common super class between {@code c1} and {@code c2}.
 * <ul>//from  w  w  w. ja va 2  s .c om
 * <li>If {@code c1} and {@code c2} are equal, then {@code c1} will be returned,
 * even if it is an interface or primitive.
 * <li>Likewise if {@code c1} is assignable from {@code c2} ({@link Class#isAssignableFrom})
 * then {@code c1} will be returned even if it is an interface, and vice versa if the
 * {@code c2} is assignable from {@code c1}.
 * <li>If the above is not true, and either argument is a primitive, then null will be returned.
 * <li>If the above is not true, and either argument is an interface, then {@link Object} will
 * be returned.
 * <li>Otherwise, the nearest superclass of both {@code c1} and {@code c2} will be returned.
 * </ul>
 */
public static @Nullable Class<?> nearestCommonSuperClass(Class<?> c1, Class<?> c2) {
    if (c1.isAssignableFrom(c2)) {
        return c1;
    } else if (c2.isAssignableFrom(c1)) {
        return c2;
    }

    // At this point we know that the common superclass cannot be c1 or c2.

    if (c1.isPrimitive() || c2.isPrimitive()) {
        return null;
    }

    if (c1.isInterface() || c2.isInterface()) {
        return Object.class;
    }

    ImmutableList<Class<?>> supers1 = superClasses(c1);
    ImmutableList<Class<?>> supers2 = superClasses(c2);

    Class<?> common = Object.class;

    for (int i = 0, end = Math.min(supers1.size(), supers2.size()); i < end; ++i) {
        Class<?> super1 = supers1.get(i);
        if (super1.equals(supers2.get(i))) {
            common = super1;
        } else {
            break;
        }
    }

    return common;
}

From source file:com.spectralogic.dsbrowser.gui.services.ds3Panel.Ds3PanelService.java

@SuppressWarnings("unchecked")
public static void showMetadata(final Ds3Common ds3Common, final Workers workers,
        final ResourceBundle resourceBundle) {
    final TreeTableView ds3TreeTableView = ds3Common.getDs3TreeTableView();
    final ImmutableList<TreeItem<Ds3TreeTableValue>> values = (ImmutableList<TreeItem<Ds3TreeTableValue>>) ds3TreeTableView
            .getSelectionModel().getSelectedItems().stream().collect(GuavaCollectors.immutableList());
    if (values.isEmpty()) {
        LOG.info(resourceBundle.getString("noFiles"));
        new LazyAlert(resourceBundle).info(resourceBundle.getString("noFiles"));
        return;//from   w  ww  .ja v a 2s.  co m
    }
    if (values.size() > 1) {
        LOG.info(resourceBundle.getString("onlySingleObjectSelectForMetadata"));
        new LazyAlert(resourceBundle).info(resourceBundle.getString("onlySingleObjectSelectForMetadata"));
        return;
    }

    final MetadataTask getMetadata = new MetadataTask(ds3Common, values);
    workers.execute(getMetadata);
    getMetadata.setOnSucceeded(SafeHandler.logHandle(event -> Platform.runLater(() -> {
        LOG.info("Launching metadata popup");
        final MetadataView metadataView = new MetadataView((Ds3Metadata) getMetadata.getValue());
        Popup.show(metadataView.getView(), resourceBundle.getString("metaDataContextMenu"));
    })));
}

From source file:de.ii.xtraplatform.feature.provider.pgis.MixAndMatch.java

public static <T> Source<T, NotUsed> create(Predicate<Pair<T, T>> matcher, Source<T, NotUsed>... sources) {
    ImmutableList<Source<T, ?>> sourcesList = ImmutableList.copyOf(sources);

    return Source.combine(sourcesList.get(0), sourcesList.get(1),
            sourcesList.size() > 2 ? sourcesList.subList(2, sourcesList.size()) : ImmutableList.of(),
            numberOfSources -> new MixAndMatchStage<>(numberOfSources, matcher));
}

From source file:de.ii.xtraplatform.feature.provider.pgis.MixAndMatch.java

public static <T> Source<T, NotUsed> create(Map<Integer, List<Integer>> sourceNesting,
        Map<Integer, Predicate<Pair<T, T>>> matchers, int mainSourceIndex, Source<T, NotUsed>... sources) {
    ImmutableList<Source<T, ?>> sourcesList = ImmutableList.copyOf(sources);

    return Source.combine(sourcesList.get(0), sourcesList.get(1),
            sourcesList.size() > 2 ? sourcesList.subList(2, sourcesList.size()) : ImmutableList.of(),
            numberOfSources -> new MixAndMatchStage<>(numberOfSources, sourceNesting, matchers,
                    mainSourceIndex));/*from w w  w.j a v  a 2s. co  m*/
}

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

/**
 * Returns an expression that returns a new {@link LinkedHashMap} containing all the given 
 * entries./*w w w.  j  a v  a 2  s .c om*/
 */
static Expression newLinkedHashMap(Iterable<? extends Expression> keys, Iterable<? extends Expression> values) {
    final ImmutableList<Expression> keysCopy = ImmutableList.copyOf(keys);
    final ImmutableList<Expression> valuesCopy = ImmutableList.copyOf(values);
    checkArgument(keysCopy.size() == valuesCopy.size());
    for (int i = 0; i < keysCopy.size(); i++) {
        checkArgument(keysCopy.get(i).resultType().getSort() == Type.OBJECT);
        checkArgument(valuesCopy.get(i).resultType().getSort() == Type.OBJECT);
    }
    final Expression construct = ConstructorRef.LINKED_HASH_MAP_SIZE
            .construct(constant(hashMapCapacity(keysCopy.size())));
    return new Expression(Type.getType(LinkedHashMap.class), Feature.NON_NULLABLE) {
        @Override
        void doGen(CodeBuilder mv) {
            construct.gen(mv);
            for (int i = 0; i < keysCopy.size(); i++) {
                Expression key = keysCopy.get(i);
                Expression value = valuesCopy.get(i);
                mv.dup();
                key.gen(mv);
                value.gen(mv);
                MethodRef.LINKED_HASH_MAP_PUT.invokeUnchecked(mv);
                mv.pop(); // pop the Object result of map.put
            }
        }
    };
}

From source file:com.github.rinde.opt.localsearch.Swaps.java

/**
 * Swap an item from <code>fromRow</code> to <code>toRow</code>. All
 * occurrences are removed from <code>fromRow</code> and will be added in
 * <code>toRow</code> at the specified indices. The modified schedule is only
 * returned if it improves over the specified <code>threshold</code> value.
 * The quality of a schedule is determined by its {@link Schedule#evaluator}.
 *
 * @param s The schedule to perform the swap on.
 * @param itemToSwap The item to swap./*w  w w.j a  v  a2s  . co  m*/
 * @param fromRow The originating row of the item.
 * @param toRow The destination row for the item.
 * @param insertionIndices The indices where the item will be inserted in the
 *          new row. The number of indices must equal the number of
 *          occurrences of item in the <code>fromRow</code>. If
 *          <code>fromRow == toRow</code> the insertion indices point to the
 *          indices of the row <b>without</b> the original item in it.
 * @param threshold The threshold value which decides whether a schedule is
 *          returned.
 * @return The swapped schedule if the cost of the new schedule is better
 *         (lower) than the threshold, {@link Optional#absent()} otherwise.
 */
static <C, T> Optional<Schedule<C, T>> swap(Schedule<C, T> s, Swap<T> swap, double threshold,
        Object2DoubleLinkedOpenHashMap<ImmutableList<T>> cache) {

    checkArgument(swap.fromRow() >= 0 && swap.fromRow() < s.routes.size(),
            "fromRow must be >= 0 and < %s, it is %s.", s.routes.size(), swap.fromRow());
    checkArgument(swap.toRow() >= 0 && swap.toRow() < s.routes.size(), "toRow must be >= 0 and < %s, it is %s.",
            s.routes.size(), swap.toRow());

    if (swap.fromRow() == swap.toRow()) {
        // 1. swap within same vehicle
        // compute cost of original ordering
        // compute cost of new ordering
        final double originalCost = s.objectiveValues.getDouble(swap.fromRow());
        final ImmutableList<T> newRoute = inListSwap(s.routes.get(swap.fromRow()), swap.toIndices(),
                swap.item());

        final double newCost = computeCost(s, swap.fromRow(), newRoute, cache);
        final double diff = newCost - originalCost;

        if (diff < threshold) {
            // it improves
            final ImmutableList<ImmutableList<T>> newRoutes = replace(s.routes, asIntList(swap.fromRow()),
                    ImmutableList.of(newRoute));
            final double newObjectiveValue = s.objectiveValue + diff;
            final DoubleList newObjectiveValues = replace(s.objectiveValues, asIntList(swap.fromRow()),
                    asDoubleList(newCost));
            return Optional.of(Schedule.create(s.context, newRoutes, s.startIndices, newObjectiveValues,
                    newObjectiveValue, s.evaluator));
        } else {
            return Optional.absent();
        }
    } else {
        // 2. swap between vehicles

        // compute cost of removal from original vehicle
        final double originalCostA = s.objectiveValues.getDouble(swap.fromRow());
        final ImmutableList<T> newRouteA = ImmutableList
                .copyOf(filter(s.routes.get(swap.fromRow()), not(equalTo(swap.item()))));
        final int itemCount = s.routes.get(swap.fromRow()).size() - newRouteA.size();
        checkArgument(itemCount > 0,
                "The item (%s) is not in row %s, hence it cannot be swapped to another " + "row.", swap.item(),
                swap.fromRow());
        checkArgument(itemCount == swap.toIndices().size(),
                "The number of occurences in the fromRow (%s) should equal the number "
                        + "of insertion indices (%s).",
                itemCount, swap.toIndices().size());

        final double newCostA = computeCost(s, swap.fromRow(), newRouteA, cache);
        final double diffA = newCostA - originalCostA;

        // compute cost of insertion in new vehicle
        final double originalCostB = s.objectiveValues.getDouble(swap.toRow());
        final ImmutableList<T> newRouteB = Insertions.insert(s.routes.get(swap.toRow()), swap.toIndices(),
                swap.item());

        final double newCostB = computeCost(s, swap.toRow(), newRouteB, cache);
        final double diffB = newCostB - originalCostB;

        final double diff = diffA + diffB;
        if (diff < threshold) {
            final IntList rows = asIntList(swap.fromRow(), swap.toRow());
            final ImmutableList<ImmutableList<T>> newRoutes = replace(s.routes, rows,
                    ImmutableList.of(newRouteA, newRouteB));
            final double newObjectiveValue = s.objectiveValue + diff;
            final DoubleList newObjectiveValues = replace(s.objectiveValues, rows,
                    asDoubleList(newCostA, newCostB));

            return Optional.of(Schedule.create(s.context, newRoutes, s.startIndices, newObjectiveValues,
                    newObjectiveValue, s.evaluator));
        } else {
            return Optional.absent();
        }
    }
}

From source file:com.siemens.sw360.commonIO.ConvertRecord.java

public static void addLicenses(LicenseService.Iface licenseClient, List<License> licensesToAdd, Logger log) {
    try {// w ww .  ja v  a2  s .c o m
        final List<License> licenses = licenseClient.getLicenses();
        final Set<String> knownLicenseNames = Sets
                .newHashSet(FluentIterable.from(licenses).transform(TypeMappings.getLicenseIdentifier()));
        final ImmutableList<License> filteredLicenses = TypeMappings.getElementsWithIdentifiersNotInSet(
                TypeMappings.getLicenseIdentifier(), knownLicenseNames, licensesToAdd);

        log.debug("Sending " + filteredLicenses.size() + " Licenses to the database!");
        final List<License> addedLicenses = licenseClient.addLicenses(filteredLicenses);

        if (addedLicenses == null) {
            log.debug("There were errors.");
        } else {
            log.debug("Everything went fine.");
        }

    } catch (TException e) {
        log.error("Error getting licenses from DB", e);
    }
}

From source file:com.google.errorprone.bugpatterns.formatstring.StrictFormatStringValidation.java

/** Helps {@code validate()} validate a format string that is declared as a method parameter. */
private static ValidationResult validateFormatStringParamter(ExpressionTree formatStringTree,
        Symbol formatStringSymbol, List<? extends ExpressionTree> args, VisitorState state) {
    if (!isFormatStringParameter(formatStringSymbol, state)) {
        return ValidationResult.create(null, String.format(
                "Format strings must be compile time constant or parameters annotated " + "@FormatString: %s",
                formatStringTree));//from  w w w. j  a va 2  s  .co  m
    }

    List<VarSymbol> ownerParams = ((MethodSymbol) formatStringSymbol.owner).getParameters();
    int ownerFormatStringIndex = ownerParams.indexOf(formatStringSymbol);

    ImmutableList.Builder<Type> ownerFormatArgTypesBuilder = ImmutableList.builder();
    for (VarSymbol paramSymbol : ownerParams.subList(ownerFormatStringIndex + 1, ownerParams.size())) {
        ownerFormatArgTypesBuilder.add(paramSymbol.type);
    }
    ImmutableList<Type> ownerFormatArgTypes = ownerFormatArgTypesBuilder.build();

    Types types = state.getTypes();
    ImmutableList.Builder<Type> calleeFormatArgTypesBuilder = ImmutableList.builder();
    for (ExpressionTree formatArgExpression : args) {
        calleeFormatArgTypesBuilder.add(types.erasure(((JCExpression) formatArgExpression).type));
    }
    ImmutableList<Type> calleeFormatArgTypes = calleeFormatArgTypesBuilder.build();

    if (ownerFormatArgTypes.size() != calleeFormatArgTypes.size()) {
        return ValidationResult.create(null,
                String.format(
                        "The number of format arguments passed "
                                + "with an @FormatString must match the number of format arguments in the "
                                + "@FormatMethod header where the format string was declared.\n\t"
                                + "Format args passed: %d\n\tFormat args expected: %d",
                        calleeFormatArgTypes.size(), ownerFormatArgTypes.size()));
    } else {
        for (int i = 0; i < calleeFormatArgTypes.size(); i++) {
            if (!ASTHelpers.isSameType(ownerFormatArgTypes.get(i), calleeFormatArgTypes.get(i), state)) {
                return ValidationResult.create(null,
                        String.format("The format argument types passed "
                                + "with an @FormatString must match the types of the format arguments in "
                                + "the @FormatMethod header where the format string was declared.\n\t"
                                + "Format arg types passed: %s\n\tFormat arg types expected: %s",
                                calleeFormatArgTypes.toArray(), ownerFormatArgTypes.toArray()));
            }
        }
    }

    // Format string usage was valid.
    return null;
}

From source file:org.locationtech.geogig.storage.datastream.FormatCommonV2.java

public static void writeFeature(RevFeature feature, DataOutput data) throws IOException {
    ImmutableList<Optional<Object>> values = feature.getValues();

    writeUnsignedVarInt(values.size(), data);

    for (Optional<Object> field : values) {
        FieldType type = FieldType.forValue(field);
        data.writeByte(type.getTag());/*from   w w w.j  av a 2 s . c  o m*/
        if (type != FieldType.NULL) {
            DataStreamValueSerializerV2.write(field, data);
        }
    }
}