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

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

Introduction

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

Prototype

boolean isEmpty();

Source Link

Document

Returns true if this list contains no elements.

Usage

From source file:com.google.devtools.build.lib.rules.cpp.CppCompileActionBuilder.java

private static Predicate<String> getNocoptPredicate(Collection<Pattern> patterns) {
    final ImmutableList<Pattern> finalPatterns = ImmutableList.copyOf(patterns);
    if (finalPatterns.isEmpty()) {
        return Predicates.alwaysTrue();
    } else {//ww  w. j a  v a2  s .c  o  m
        return new Predicate<String>() {
            @Override
            public boolean apply(String option) {
                for (Pattern pattern : finalPatterns) {
                    if (pattern.matcher(option).matches()) {
                        return false;
                    }
                }

                return true;
            }
        };
    }
}

From source file:io.mesosphere.mesos.util.CassandraFrameworkProtosUtils.java

public static Optional<Double> maxResourceValueDouble(@NotNull final List<Resource> resource) {
    ImmutableList<Double> values = from(resource).transform(toDoubleResourceValue()).toList();
    if (values.isEmpty()) {
        return Optional.absent();
    } else {/*from   w w  w.  j a  v a 2 s  . co m*/
        return Optional.of(Collections.max(values));
    }
}

From source file:org.geogit.api.RevTreeImpl.java

public static RevTreeImpl createLeafTree(ObjectId id, long size, ImmutableList<Node> features,
        ImmutableList<Node> trees) {

    Preconditions.checkNotNull(id);//  w w w .ja v a  2 s  .c  o m
    Preconditions.checkNotNull(features);
    Preconditions.checkNotNull(trees);

    Optional<ImmutableList<Node>> f = Optional.absent();
    Optional<ImmutableList<Node>> t = Optional.absent();
    if (!features.isEmpty()) {
        f = Optional.of(features);
    }
    if (!trees.isEmpty()) {
        t = Optional.of(trees);
    }
    return new LeafTree(id, size, f, t);
}

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

public static void showPhysicalPlacement(final Ds3Common ds3Common, final Workers workers,
        final ResourceBundle resourceBundle) {
    ImmutableList<TreeItem<Ds3TreeTableValue>> tempValues = ds3Common.getDs3TreeTableView().getSelectionModel()
            .getSelectedItems().stream().collect(GuavaCollectors.immutableList());
    final TreeItem<Ds3TreeTableValue> root = ds3Common.getDs3TreeTableView().getRoot();
    if (tempValues.isEmpty() && (root == null || root.getValue() != null)) {
        LOG.info(resourceBundle.getString("nothingSelected"));
        new LazyAlert(resourceBundle).info(resourceBundle.getString("nothingSelected"));
        return;//w  w w . ja  va  2s.  co m
    } else if (tempValues.isEmpty()) {
        final ImmutableList.Builder<TreeItem<Ds3TreeTableValue>> builder = ImmutableList.builder();
        tempValues = builder.add(root).build().asList();

    }
    final ImmutableList<TreeItem<Ds3TreeTableValue>> values = tempValues;
    if (values.size() > 1) {
        LOG.info(resourceBundle.getString("onlySingleObjectSelectForPhysicalPlacement"));
        new LazyAlert(resourceBundle)
                .info(resourceBundle.getString("onlySingleObjectSelectForPhysicalPlacement"));
        return;
    }

    final PhysicalPlacementTask getPhysicalPlacement = new PhysicalPlacementTask(ds3Common, values, workers);

    workers.execute(getPhysicalPlacement);
    getPhysicalPlacement.setOnSucceeded(SafeHandler.logHandle(event -> Platform.runLater(() -> {
        LOG.info("Launching PhysicalPlacement popup");
        PhysicalPlacementPopup.show((PhysicalPlacement) getPhysicalPlacement.getValue(), resourceBundle);
    })));
}

From source file:de.metas.ui.web.view.descriptor.annotation.ViewColumnHelper.java

private static ClassViewDescriptor createClassViewDescriptor(@NonNull final Class<?> dataType) {
    @SuppressWarnings("unchecked")
    final Set<Field> fields = ReflectionUtils.getAllFields(dataType,
            ReflectionUtils.withAnnotations(ViewColumn.class));

    final ImmutableList<ClassViewColumnDescriptor> columns = fields.stream()
            .map(field -> createClassViewColumnDescriptor(field)).collect(ImmutableList.toImmutableList());
    if (columns.isEmpty()) {
        return ClassViewDescriptor.EMPTY;
    }// www. j  ava2s  . co  m

    return ClassViewDescriptor.builder().columns(columns).build();

}

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

/**
 * Returns an expression that returns a new {@link ArrayList} containing all the given items.
 */// w ww . ja va2s  .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:org.eclipse.milo.opcua.sdk.client.session.states.AbstractSessionState.java

private static void transferSubscriptions(Fsm fsm, OpcUaSession session,
        CompletableFuture<OpcUaSession> sessionFuture) {

    OpcUaClient client = fsm.getClient();
    UaTcpStackClient stackClient = client.getStackClient();
    OpcUaSubscriptionManager subscriptionManager = client.getSubscriptionManager();
    ImmutableList<UaSubscription> subscriptions = subscriptionManager.getSubscriptions();

    if (subscriptions.isEmpty()) {
        fsm.fireEvent(new TransferSuccessEvent(session, sessionFuture));
        return;// www  . j a v a2 s  .c  o  m
    }

    UInteger[] subscriptionIdsArray = subscriptions.stream().map(UaSubscription::getSubscriptionId)
            .toArray(UInteger[]::new);

    TransferSubscriptionsRequest request = new TransferSubscriptionsRequest(
            client.newRequestHeader(session.getAuthenticationToken(), REQUEST_TIMEOUT), subscriptionIdsArray,
            true);

    LOGGER.debug("Sending TransferSubscriptionsRequest...");

    stackClient.<TransferSubscriptionsResponse>sendRequest(request).whenCompleteAsync((tsr, ex) -> {
        if (tsr != null) {
            List<TransferResult> results = l(tsr.getResults());

            client.getConfig().getExecutor().execute(() -> {
                for (int i = 0; i < results.size(); i++) {
                    TransferResult result = results.get(i);

                    if (!result.getStatusCode().isGood()) {
                        UaSubscription subscription = subscriptions.get(i);

                        subscriptionManager.transferFailed(subscription.getSubscriptionId(),
                                result.getStatusCode());
                    }
                }
            });

            if (LOGGER.isDebugEnabled()) {
                Stream<UInteger> subscriptionIds = subscriptions.stream()
                        .map(UaSubscription::getSubscriptionId);
                Stream<StatusCode> statusCodes = results.stream().map(TransferResult::getStatusCode);

                String[] ss = StreamUtils
                        .zip(subscriptionIds, statusCodes,
                                (i, s) -> String.format("id=%s/%s", i,
                                        StatusCodes.lookup(s.getValue()).map(sa -> sa[0]).orElse(s.toString())))
                        .toArray(String[]::new);

                LOGGER.debug("TransferSubscriptions results: {}", Arrays.toString(ss));
            }

            fsm.fireEvent(new TransferSuccessEvent(session, sessionFuture));
        } else {
            StatusCode statusCode = UaException.extract(ex).map(UaException::getStatusCode)
                    .orElse(StatusCode.BAD);

            // Bad_ServiceUnsupported is the correct response when transfers aren't supported but
            // server implementations tend to interpret the spec in their own unique way...
            if (statusCode.getValue() == StatusCodes.Bad_NotImplemented
                    || statusCode.getValue() == StatusCodes.Bad_NotSupported
                    || statusCode.getValue() == StatusCodes.Bad_OutOfService
                    || statusCode.getValue() == StatusCodes.Bad_ServiceUnsupported) {

                LOGGER.debug("TransferSubscriptions not supported: {}", statusCode);

                client.getConfig().getExecutor().execute(() -> {
                    // transferFailed() will remove the subscription, but that is okay
                    // because the list from getSubscriptions() above is a copy.
                    for (UaSubscription subscription : subscriptions) {
                        subscriptionManager.transferFailed(subscription.getSubscriptionId(), statusCode);
                    }
                });

                fsm.fireEvent(new TransferSuccessEvent(session, sessionFuture));
            } else {
                LOGGER.debug("TransferSubscriptions failed: {}", statusCode);

                fsm.fireEvent(new TransferFailureEvent(ex, session, sessionFuture));
            }
        }
    }, stackClient.getExecutorService());
}

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;// www .j av  a  2 s .co 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

private static Expression doShortCircuitingLogicalOperator(
        final ImmutableList<? extends Expression> expressions, final boolean isOrOperator) {
    checkArgument(!expressions.isEmpty());
    for (Expression expr : expressions) {
        expr.checkAssignableTo(Type.BOOLEAN_TYPE);
    }/*from   w  w w  .j a v  a2  s  . c  om*/
    if (expressions.size() == 1) {
        return expressions.get(0);
    }

    return new Expression(Type.BOOLEAN_TYPE,
            Expression.areAllCheap(expressions) ? Features.of(Feature.CHEAP) : Features.of()) {
        @Override
        void doGen(CodeBuilder adapter) {
            Label end = new Label();
            Label shortCircuit = new Label();
            for (int i = 0; i < expressions.size(); i++) {
                Expression expr = expressions.get(i);
                expr.gen(adapter);
                if (i == expressions.size() - 1) {
                    // if we are the last one, just goto end. Whatever the result of the last expression is
                    // determines the result of the whole expression (when all prior tests fail).
                    adapter.goTo(end);
                } else {
                    adapter.ifZCmp(isOrOperator ? Opcodes.IFNE : Opcodes.IFEQ, shortCircuit);
                }
            }
            adapter.mark(shortCircuit);
            adapter.pushBoolean(isOrOperator); // default for || is true && is false
            adapter.mark(end);
        }
    };
}

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

public static RevTree readTree(ObjectId id, DataInput in) throws IOException {
    final long size = in.readLong();
    final int treeCount = in.readInt();
    final ImmutableList.Builder<Node> featuresBuilder = new ImmutableList.Builder<Node>();
    final ImmutableList.Builder<Node> treesBuilder = new ImmutableList.Builder<Node>();
    final SortedMap<Integer, Bucket> buckets = new TreeMap<Integer, Bucket>();

    final int nFeatures = in.readInt();
    for (int i = 0; i < nFeatures; i++) {
        Node n = readNode(in);/*from  w  w  w  .  ja v  a  2s .c o  m*/
        if (n.getType() != RevObject.TYPE.FEATURE) {
            throw new IllegalStateException("Non-feature node in tree's feature list.");
        }
        featuresBuilder.add(n);
    }

    final int nTrees = in.readInt();
    for (int i = 0; i < nTrees; i++) {
        Node n = readNode(in);
        if (n.getType() != RevObject.TYPE.TREE) {
            throw new IllegalStateException("Non-tree node in tree's subtree list.");
        }
        treesBuilder.add(n);
    }

    final int nBuckets = in.readInt();
    for (int i = 0; i < nBuckets; i++) {
        int key = in.readInt();
        Bucket bucket = readBucket(in);
        buckets.put(key, bucket);
    }

    ImmutableList<Node> trees = treesBuilder.build();
    ImmutableList<Node> features = featuresBuilder.build();
    if (nTrees == 0 && nFeatures == 0 && nBuckets == 0) {
        return RevTree.EMPTY;
    } else if (trees.isEmpty() && features.isEmpty()) {
        return RevTreeImpl.createNodeTree(id, size, treeCount, buckets);
    } else if (buckets.isEmpty()) {
        return RevTreeImpl.createLeafTree(id, size, features, trees);
    } else {
        throw new IllegalArgumentException("Tree has mixed buckets and nodes; this is not supported.");
    }
}