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.devtools.kythe.analyzers.jvm.ClassFileIndexer.java

private static VName getEnclosingJar(ImmutableList<VName> enclosingJars, CompilationUnit.FileInput file) {
    JarEntryDetails jarEntryDetails = null;
    for (Any details : file.getDetailsList()) {
        if (details.getTypeUrl().equals(JAR_ENTRY_DETAILS_URL)) {
            try {
                jarEntryDetails = JarEntryDetails.parseFrom(details.getValue());
            } catch (InvalidProtocolBufferException ipbe) {
                logger.atWarning().withCause(ipbe).log("Error unpacking JarEntryDetails");
            }/*from  w  w w .j a v  a2 s  .c o  m*/
        }
    }
    if (jarEntryDetails == null) {
        return null;
    }
    int idx = jarEntryDetails.getJarContainer();
    if (idx < 0 || idx >= enclosingJars.size()) {
        logger.atWarning().log("JarEntryDetails index out of range: %s (jars: %s)", jarEntryDetails,
                enclosingJars);
        return null;
    }
    return enclosingJars.get(idx);
}

From source file:com.google.devtools.build.lib.query2.engine.BinaryOperatorExpression.java

/**
 * Evaluates an expression of the form "e1 - e2 - ... - eK" by noting its equivalence to
 * "e1 - (e2 + ... + eK)" and evaluating the subexpressions on the right-hand-side in parallel.
 *//*from ww w  .ja  v a  2 s.  co  m*/
private static <T> void parEvalMinus(ImmutableList<QueryExpression> operands, QueryEnvironment<T> env,
        VariableContext<T> context, ThreadSafeCallback<T> callback, ForkJoinPool forkJoinPool)
        throws QueryException, InterruptedException {
    final Set<T> lhsValue = Sets.newConcurrentHashSet(QueryUtil.evalAll(env, context, operands.get(0)));
    ThreadSafeCallback<T> subtractionCallback = new ThreadSafeCallback<T>() {
        @Override
        public void process(Iterable<T> partialResult) throws QueryException, InterruptedException {
            for (T target : partialResult) {
                lhsValue.remove(target);
            }
        }
    };
    parEvalPlus(operands.subList(1, operands.size()), env, context, subtractionCallback, forkJoinPool);
    callback.process(lhsValue);
}

From source file:org.eclipse.sw360.commonIO.ConvertRecord.java

public static void addLicenses(LicenseService.Iface licenseClient, List<License> licensesToAdd, Logger log,
        User user) {/*w  w  w  .  j a  v  a2 s  .  co m*/
    try {
        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, user);

        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:org.glowroot.agent.embedded.init.ConfigRepositoryImpl.java

private static ImmutableList<Integer> fix(ImmutableList<Integer> thisList, List<Integer> defaultList) {
    if (thisList.size() >= defaultList.size()) {
        return thisList.subList(0, defaultList.size());
    }/*from   ww w.j a  va 2  s  . com*/
    List<Integer> correctedList = Lists.newArrayList(thisList);
    for (int i = thisList.size(); i < defaultList.size(); i++) {
        correctedList.add(defaultList.get(i));
    }
    return ImmutableList.copyOf(correctedList);
}

From source file:com.google.gerrit.server.update.NoteDbBatchUpdate.java

static void execute(ImmutableList<NoteDbBatchUpdate> updates, BatchUpdateListener listener,
        @Nullable RequestId requestId, boolean dryrun) throws UpdateException, RestApiException {
    if (updates.isEmpty()) {
        return;//from  w ww. j  a  v  a 2 s .  c  o m
    }
    setRequestIds(updates, requestId);

    try {
        List<CheckedFuture<?, IOException>> indexFutures = new ArrayList<>();
        List<ChangesHandle> handles = new ArrayList<>(updates.size());
        Order order = getOrder(updates, listener);
        try {
            switch (order) {
            case REPO_BEFORE_DB:
                for (NoteDbBatchUpdate u : updates) {
                    u.executeUpdateRepo();
                }
                listener.afterUpdateRepos();
                for (NoteDbBatchUpdate u : updates) {
                    handles.add(u.executeChangeOps(dryrun));
                }
                for (ChangesHandle h : handles) {
                    h.execute();
                    indexFutures.addAll(h.startIndexFutures());
                }
                listener.afterUpdateRefs();
                listener.afterUpdateChanges();
                break;

            case DB_BEFORE_REPO:
                // Call updateChange for each op before updateRepo, but defer executing the
                // NoteDbUpdateManager until after calling updateRepo. They share an inserter and
                // BatchRefUpdate, so it will all execute as a single batch. But we have to let
                // NoteDbUpdateManager actually execute the update, since it has to interleave it
                // properly with All-Users updates.
                //
                // TODO(dborowitz): This may still result in multiple updates to All-Users, but that's
                // currently not a big deal because multi-change batches generally aren't affecting
                // drafts anyway.
                for (NoteDbBatchUpdate u : updates) {
                    handles.add(u.executeChangeOps(dryrun));
                }
                for (NoteDbBatchUpdate u : updates) {
                    u.executeUpdateRepo();
                }
                for (ChangesHandle h : handles) {
                    // TODO(dborowitz): This isn't quite good enough: in theory updateRepo may want to
                    // see the results of change meta commands, but they aren't actually added to the
                    // BatchUpdate until the body of execute. To fix this, execute needs to be split up
                    // into a method that returns a BatchRefUpdate before execution. Not a big deal at the
                    // moment, because this order is only used for deleting changes, and those updateRepo
                    // implementations definitely don't need to observe the updated change meta refs.
                    h.execute();
                    indexFutures.addAll(h.startIndexFutures());
                }
                break;
            default:
                throw new IllegalStateException("invalid execution order: " + order);
            }
        } finally {
            for (ChangesHandle h : handles) {
                h.close();
            }
        }

        ChangeIndexer.allAsList(indexFutures).get();

        // Fire ref update events only after all mutations are finished, since callers may assume a
        // patch set ref being created means the change was created, or a branch advancing meaning
        // some changes were closed.
        updates.stream().filter(u -> u.batchRefUpdate != null)
                .forEach(u -> u.gitRefUpdated.fire(u.project, u.batchRefUpdate, u.getAccount().orElse(null)));

        if (!dryrun) {
            for (NoteDbBatchUpdate u : updates) {
                u.executePostOps();
            }
        }
    } catch (Exception e) {
        wrapAndThrowException(e);
    }
}

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

/**
 * Returns an expression that returns a new {@link ArrayList} containing all the given items.
 *//*from w  w  w . j a v a 2s .c  o  m*/
static Expression asList(Iterable<? extends Expression> items) {
    final ImmutableList<Expression> copy = ImmutableList.copyOf(items);
    if (copy.isEmpty()) {
        return MethodRef.IMMUTABLE_LIST_OF.invoke();
    }
    // Note, we cannot neccesarily use ImmutableList for anything besides the empty list because
    // we may need to put a null in it.
    final Expression construct = ConstructorRef.ARRAY_LIST_SIZE.construct(constant(copy.size()));
    return new Expression(Type.getType(ArrayList.class), Feature.NON_NULLABLE) {
        @Override
        void doGen(CodeBuilder mv) {
            construct.gen(mv);
            for (Expression child : copy) {
                mv.dup();
                child.gen(mv);
                MethodRef.ARRAY_LIST_ADD.invokeUnchecked(mv);
                mv.pop(); // pop the bool result of arraylist.add
            }
        }
    };
}

From source file:com.matthewmitchell.nubitsj.crypto.DeterministicKey.java

public static DeterministicKey deserialize(@Nullable DeterministicKey parent, byte[] serializedKey) {
    ByteBuffer buffer = ByteBuffer.wrap(serializedKey);
    int header = buffer.getInt();
    if (header != HEADER_PRIV && header != HEADER_PUB)
        throw new IllegalArgumentException("Unknown header bytes: " + toBase58(serializedKey).substring(0, 4));
    boolean pub = header == HEADER_PUB;
    byte depth = buffer.get();
    byte[] parentFingerprint = new byte[4];
    buffer.get(parentFingerprint);/*  w  w w.j a v  a  2s  . c  o m*/
    final int i = buffer.getInt();
    final ChildNumber childNumber = new ChildNumber(i);
    ImmutableList<ChildNumber> path;
    if (parent != null) {
        if (Arrays.equals(parentFingerprint, HDUtils.longTo4ByteArray(0)))
            throw new IllegalArgumentException("Parent was provided but this key doesn't have one");
        if (!Arrays.equals(parent.getFingerprint(), parentFingerprint))
            throw new IllegalArgumentException("Parent fingerprints don't match");
        path = HDUtils.append(parent.getPath(), childNumber);
        if (path.size() != depth)
            throw new IllegalArgumentException("Depth does not match");
    } else {
        if (depth == 0) {
            path = ImmutableList.of();
        } else if (depth == 1) {
            // We have been given a key that is not a root key, yet we also don't have any object representing
            // the parent. This can happen when deserializing an account key for a watching wallet. In this case,
            // we assume that the parent has a path of zero.
            path = ImmutableList.of(childNumber);
        } else {
            throw new IllegalArgumentException("Depth is " + depth + " and no parent key was provided, so we "
                    + "cannot reconstruct the key path from the provided data.");
        }
    }
    byte[] chainCode = new byte[32];
    buffer.get(chainCode);
    byte[] data = new byte[33];
    buffer.get(data);
    checkArgument(!buffer.hasRemaining(), "Found unexpected data in key");
    if (pub) {
        ECPoint point = ECKey.CURVE.getCurve().decodePoint(data);
        return new DeterministicKey(path, chainCode, point, null, parent);
    } else {
        return new DeterministicKey(path, chainCode, new BigInteger(1, data), parent);
    }
}

From source file:grakn.core.graql.reasoner.plan.ResolutionQueryPlan.java

/**
 * compute the query resolution plan - list of queries ordered by their cost as computed by the graql traversal planner
 * @return list of prioritised queries//from  w  w w  . jav a2 s . c  om
 */
private static ImmutableList<ReasonerQueryImpl> queryPlan(ReasonerQueryImpl query) {
    ResolutionPlan resolutionPlan = query.resolutionPlan();

    ImmutableList<Atom> plan = resolutionPlan.plan();
    TransactionOLTP tx = query.tx();
    LinkedList<Atom> atoms = new LinkedList<>(plan);
    List<ReasonerQueryImpl> queries = new LinkedList<>();

    List<Atom> nonResolvableAtoms = new ArrayList<>();
    while (!atoms.isEmpty()) {
        Atom top = atoms.remove();
        if (top.isRuleResolvable()) {
            if (!nonResolvableAtoms.isEmpty()) {
                queries.add(ReasonerQueries.create(nonResolvableAtoms, tx));
                nonResolvableAtoms.clear();
            }
            queries.add(ReasonerQueries.atomic(top));
        } else {
            nonResolvableAtoms.add(top);
            if (atoms.isEmpty())
                queries.add(ReasonerQueries.create(nonResolvableAtoms, tx));
        }
    }

    boolean refine = plan.size() != queries.size() && !query.requiresSchema();
    return refine ? refine(queries) : ImmutableList.copyOf(queries);
}

From source file:org.neoscoinj.crypto.DeterministicKey.java

/**
  * Deserialize an HD Key./*from w  w  w  .  ja  v  a2 s  . c  om*/
 * @param parent The parent node in the given key's deterministic hierarchy.
 */
public static DeterministicKey deserialize(NetworkParameters params, byte[] serializedKey,
        @Nullable DeterministicKey parent) {
    ByteBuffer buffer = ByteBuffer.wrap(serializedKey);
    int header = buffer.getInt();
    if (header != params.getBip32HeaderPriv() && header != params.getBip32HeaderPub())
        throw new IllegalArgumentException("Unknown header bytes: " + toBase58(serializedKey).substring(0, 4));
    boolean pub = header == params.getBip32HeaderPub();
    byte depth = buffer.get();
    byte[] parentFingerprint = new byte[4];
    buffer.get(parentFingerprint);
    final int i = buffer.getInt();
    final ChildNumber childNumber = new ChildNumber(i);
    ImmutableList<ChildNumber> path;
    if (parent != null) {
        if (Arrays.equals(parentFingerprint, HDUtils.longTo4ByteArray(0)))
            throw new IllegalArgumentException("Parent was provided but this key doesn't have one");
        if (!Arrays.equals(parent.getFingerprint(), parentFingerprint))
            throw new IllegalArgumentException("Parent fingerprints don't match");
        path = HDUtils.append(parent.getPath(), childNumber);
        if (path.size() != depth)
            throw new IllegalArgumentException("Depth does not match");
    } else {
        if (depth >= 1)
            // We have been given a key that is not a root key, yet we lack any object representing the parent.
            // This can happen when deserializing an account key for a watching wallet. In this case, we assume that
            // the client wants to conceal the key's position in the hierarchy. The parent is deemed to be the
            // root of the hierarchy.
            path = ImmutableList.of(childNumber);
        else
            path = ImmutableList.of();
    }
    byte[] chainCode = new byte[32];
    buffer.get(chainCode);
    byte[] data = new byte[33];
    buffer.get(data);
    checkArgument(!buffer.hasRemaining(), "Found unexpected data in key");
    if (pub) {
        ECPoint point = ECKey.CURVE.getCurve().decodePoint(data);
        return new DeterministicKey(path, chainCode, new LazyECPoint(point), null, parent);
    } else {
        return new DeterministicKey(path, chainCode, new BigInteger(1, data), parent);
    }
}

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

/**
 * Returns an expression that returns a new {@code ImmutableList} containing the given items.
 *
 * <p>NOTE: {@code ImmutableList} rejects null elements.
 *///  w  w  w.j  a v a  2s. c  o m
public static Expression asImmutableList(Iterable<? extends Expression> items) {
    ImmutableList<Expression> copy = ImmutableList.copyOf(items);
    if (copy.size() < MethodRef.IMMUTABLE_LIST_OF.size()) {
        return MethodRef.IMMUTABLE_LIST_OF.get(copy.size()).invoke(copy);
    }
    ImmutableList<Expression> explicit = copy.subList(0, MethodRef.IMMUTABLE_LIST_OF.size());
    Expression remainder = asArray(OBJECT_ARRAY_TYPE,
            copy.subList(MethodRef.IMMUTABLE_LIST_OF.size(), copy.size()));
    return MethodRef.IMMUTABLE_LIST_OF_ARRAY.invoke(Iterables.concat(explicit, ImmutableList.of(remainder)));
}