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.opengamma.strata.collect.io.CsvIterator.java

/**
 * Checks whether there is another row in the CSV file.
 * // w w w.  ja v a 2  s.c  o m
 * @return true if there is another row, false if not
 * @throws UncheckedIOException if an IO exception occurs
 * @throws IllegalArgumentException if the file cannot be parsed
 */
@Override
public boolean hasNext() {
    if (nextRow != null) {
        return true;
    } else {
        String line = null;
        while ((line = Unchecked.wrap(() -> reader.readLine())) != null) {
            ImmutableList<String> fields = CsvFile.parseLine(line, separator);
            if (!fields.isEmpty()) {
                nextRow = new CsvRow(headers, searchHeaders, fields);
                return true;
            }
        }
        return false;
    }
}

From source file:org.apache.james.jmap.methods.SetFilterMethod.java

private void ensureNoMultipleMailboxesRules(ImmutableList<Rule> rules) throws MultipleMailboxIdException {
    ImmutableList<Rule.Id> idWithMultipleMailboxes = rules.stream()
            .filter(rule -> rule.getAction().getAppendInMailboxes().getMailboxIds().size() > 1).map(Rule::getId)
            .collect(ImmutableList.toImmutableList());

    if (!idWithMultipleMailboxes.isEmpty()) {
        throw new MultipleMailboxIdException(idWithMultipleMailboxes);
    }//from  w  w  w. j  a v a  2 s.  c o m
}

From source file:net.bunselmeyer.mongo.maven.plugin.MigrateMojo.java

public void execute() throws MojoExecutionException {

    if (StringUtils.isBlank(host)) {
        host = "localhost";
    }/*from   w w w . j  a  va 2 s.  c  o m*/

    Set<Class<? extends Migration>> allMigrations = scanProjectForMigrations();

    ImmutableListMultimap<MIGRATION_CHECK, MigrationDetails> statusIndex = buildStatusIndex(allMigrations);

    ImmutableList<MigrationDetails> errors = statusIndex.get(MIGRATION_CHECK.ERROR);
    if (!errors.isEmpty()) {
        getLog().error("Fail: Please correct the following issues...");
        for (MigrationDetails error : errors) {
            getLog().error("    " + error.migration.getName() + ": " + error.message);
        }
        return;
    }

    ImmutableList<MigrationDetails> warnings = statusIndex.get(MIGRATION_CHECK.WARNING);
    if (!warnings.isEmpty()) {
        getLog().warn("Warnings...");
        for (MigrationDetails warning : warnings) {
            getLog().warn("    " + warning.migration.getName() + ": " + warning.message);
        }
    }

    ImmutableList<MigrationDetails> goodMigrations = statusIndex.get(MIGRATION_CHECK.GOOD);

    getLog().info("Found " + goodMigrations.size() + " migrations.");

    ImmutableListMultimap<String, MigrationDetails> index = buildIndex(goodMigrations);

    List<String> keys = Lists.newArrayList(index.keySet());
    Collections.sort(keys);

    for (String connectionDef : keys) {
        runMigrations(Lists.newArrayList(index.get(connectionDef)));
    }
}

From source file:org.elasticsearch.action.admin.cluster.snapshots.status.TransportSnapshotsStatusAction.java

@Override
protected void masterOperation(final SnapshotsStatusRequest request, final ClusterState state,
        final ActionListener<SnapshotsStatusResponse> listener) throws ElasticsearchException {
    ImmutableList<SnapshotMetaData.Entry> currentSnapshots = snapshotsService
            .currentSnapshots(request.repository(), request.snapshots());

    if (currentSnapshots.isEmpty()) {
        listener.onResponse(buildResponse(request, currentSnapshots, null));
        return;// w  ww. ja  v a2s .  c  o m
    }

    Set<String> nodesIds = newHashSet();
    for (SnapshotMetaData.Entry entry : currentSnapshots) {
        for (SnapshotMetaData.ShardSnapshotStatus status : entry.shards().values()) {
            if (status.nodeId() != null) {
                nodesIds.add(status.nodeId());
            }
        }
    }

    if (!nodesIds.isEmpty()) {
        // There are still some snapshots running - check their progress
        SnapshotId[] snapshotIds = new SnapshotId[currentSnapshots.size()];
        for (int i = 0; i < currentSnapshots.size(); i++) {
            snapshotIds[i] = currentSnapshots.get(i).snapshotId();
        }

        transportNodesSnapshotsStatus.status(nodesIds.toArray(new String[nodesIds.size()]), snapshotIds,
                request.masterNodeTimeout(),
                new ActionListener<TransportNodesSnapshotsStatus.NodesSnapshotStatus>() {
                    @Override
                    public void onResponse(
                            TransportNodesSnapshotsStatus.NodesSnapshotStatus nodeSnapshotStatuses) {
                        try {
                            ImmutableList<SnapshotMetaData.Entry> currentSnapshots = snapshotsService
                                    .currentSnapshots(request.repository(), request.snapshots());
                            listener.onResponse(buildResponse(request, currentSnapshots, nodeSnapshotStatuses));
                        } catch (Throwable e) {
                            listener.onFailure(e);
                        }
                    }

                    @Override
                    public void onFailure(Throwable e) {
                        listener.onFailure(e);
                    }
                });
    } else {
        // We don't have any in-progress shards, just return current stats
        listener.onResponse(buildResponse(request, currentSnapshots, null));
    }

}

From source file:org.apache.james.transport.mailets.RecipientRewriteTableProcessor.java

private void forwardToRemoteAddress(MailAddress sender, MailAddress recipient, MimeMessage message,
        ImmutableList<MailAddress> mailAddresses) throws MessagingException {
    ImmutableList<MailAddress> remoteAddress = FluentIterable.from(mailAddresses).filter(isNotLocalServer())
            .toList();/* w ww.  ja va 2  s .c o  m*/

    if (!remoteAddress.isEmpty()) {
        try {
            mailetContext.sendMail(sender, remoteAddress, message);
            mailetContext.log(LogLevel.INFO, "Mail for " + recipient + " forwarded to " + remoteAddress);
        } catch (MessagingException ex) {
            mailetContext.log(LogLevel.WARN, "Error forwarding mail to " + remoteAddress);
        }
    }
}

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

private WriteBuildInfoPropertiesAction getHeader(BuildInfoContext context, BuildConfiguration config,
        PathFragment propertyFileName, ImmutableList<Artifact> inputs, BuildInfoPropertiesTranslator translator,
        boolean includeVolatile, boolean includeNonVolatile) {
    Root outputPath = config.getIncludeDirectory(RepositoryName.MAIN);
    final Artifact output = context.getBuildInfoArtifact(propertyFileName, outputPath,
            includeVolatile && !inputs.isEmpty() ? BuildInfoType.NO_REBUILD
                    : BuildInfoType.FORCE_REBUILD_IF_CHANGED);
    return new WriteBuildInfoPropertiesAction(inputs, output, translator, includeVolatile, includeNonVolatile,
            getTimestampFormatter());/*from   w  ww. java2  s  .  c  om*/
}

From source file:com.facebook.buck.event.listener.RenderingConsole.java

@VisibleForTesting
synchronized void render() {
    LOG.verbose("Rendering");
    int previousNumLinesPrinted = lastNumLinesPrinted;
    ImmutableList<String> lines = delegate.createSuperLinesAtTime(clock.currentTimeMillis());
    boolean shouldRender = isRendering() && (previousNumLinesPrinted != 0 || !lines.isEmpty());

    ImmutableList.Builder<String> logLines = ImmutableList.builder();
    String line;/*from   ww w .jav a 2 s .  co  m*/
    while ((line = pendingLogLines.poll()) != null) {
        logLines.add(line);
        shouldRender = true;
    }
    lastNumLinesPrinted = lines.size();

    // Synchronize on the DirtyPrintStreamDecorator to prevent interlacing of output.
    // We don't log immediately so we avoid locking the console handler to avoid deadlocks.
    boolean stderrDirty;
    boolean stdoutDirty;
    // TODO(cjhopman): This synchronization is likely useless.
    synchronized (console.getStdErr()) {
        synchronized (console.getStdOut()) {
            // If another source has written to stderr, stop rendering with the SuperConsole.
            // We need to do this to keep our updates consistent. We don't do this with stdout
            // because we don't use it directly except in a couple of cases, where the
            // synchronization in DirtyPrintStreamDecorator should be sufficient

            // TODO(cjhopman): We should probably only stop rendering the super lines and continue
            // rendering log lines.
            stderrDirty = console.getStdErr().isDirty();
            stdoutDirty = console.getStdOut().isDirty();
            if (stderrDirty || stdoutDirty) {
                stopRenderScheduler();
            } else if (shouldRender) {
                String fullFrame = renderFullFrame(logLines.build(), lines, previousNumLinesPrinted);
                console.getStdErr().getRawStream().print(fullFrame);
            }
        }
    }
    if (stderrDirty) {
        LOG.debug("Stopping console output (stderr was dirty).");
    }
}

From source file:com.google.caliper.options.ParsedOptions.java

@Leftovers
private void setLeftovers(ImmutableList<String> leftovers) throws InvalidCommandException {
    if (leftovers.isEmpty()) {
        throw new InvalidCommandException("No benchmark class specified");
    }/*from w w w .  jav a 2  s . c  o  m*/
    if (leftovers.size() > 1) {
        throw new InvalidCommandException("Extra stuff, expected only class name: " + leftovers);
    }
    this.benchmarkClassName = leftovers.get(0);
}

From source file:com.amazonaws.services.kinesis.stormspout.KinesisSpout.java

@Override
public void nextTuple() {
    synchronized (stateManager) {
        // Task has no assignments.
        if (!stateManager.hasGetters()) {
            // Sleep here for a bit, so we don't consume too much cpu.
            try {
                Thread.sleep(emptyRecordListSleepTimeMillis);
            } catch (InterruptedException e) {
                LOG.debug(this + " sleep was interrupted.");
            }/*w w  w  .  j  a v  a  2 s .c  o  m*/
            return;
        }

        final IShardGetter getter = stateManager.getNextGetter();
        String currentShardId = getter.getAssociatedShard();
        Record rec = null;
        boolean isRetry = false;

        if (stateManager.shouldRetry(currentShardId)) {
            safeMetricIncrement(retryCount);
            rec = stateManager.recordToRetry(currentShardId);
            if (LOG.isDebugEnabled()) {
                LOG.debug("ShardId " + currentShardId + ": Re-emitting record with partition key "
                        + rec.getPartitionKey() + ", sequence number " + rec.getSequenceNumber());
            }
            isRetry = true;
        } else {
            final Records records = getter.getNext(1);

            if (records.getMillisBehindLatest() >= 0) {
                safeMetricAssign(millisBehindLastMetric, records.getMillisBehindLatest());
            }

            final ImmutableList<Record> recordList = records.getRecords();

            if ((recordList != null) && (!recordList.isEmpty())) {
                rec = recordList.get(0);
            }
            if (records.isReshard()) {
                LOG.info(this + " detected reshard event for shard " + currentShardId);
                stateManager.handleReshard();
            }
        }

        if (rec != null) {
            // Copy record (ByteBuffer.duplicate()) so bolts in the same JVM don't affect the object (e.g. retries)
            Record recordToEmit = copyRecord(rec);
            List<Object> tuple = config.getScheme().deserialize(recordToEmit);
            LOG.info(this + " emitting record with seqnum " + recordToEmit.getSequenceNumber() + " from shard "
                    + currentShardId + " with data: " + tuple);
            collector.emit(tuple,
                    MessageIdUtil.constructMessageId(currentShardId, recordToEmit.getSequenceNumber()));
            stateManager.emit(currentShardId, recordToEmit, isRetry);
        } else {
            // Sleep here for a bit if there were no records to emit.
            try {
                Thread.sleep(emptyRecordListSleepTimeMillis);
            } catch (InterruptedException e) {
                LOG.debug(this + " sleep was interrupted.");
            }
        }

        // Do periodic ZK commit of shard states.
        if (System.currentTimeMillis() - lastCommitTime >= config.getCheckpointIntervalMillis()) {
            LOG.debug(this + " committing local shard states to ZooKeeper.");

            stateManager.commitShardStates();
            lastCommitTime = System.currentTimeMillis();
        } else {
            LOG.debug(this + " Not committing to ZooKeeper.");
        }
    }
}

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

private RequiredProviders(Constraint constraint, ImmutableList<ImmutableSet<Class<?>>> nativeProviders,
        ImmutableList<ImmutableSet<SkylarkProviderIdentifier>> skylarkProviders) {
    this.constraint = constraint;

    Preconditions.checkState(constraint.equals(Constraint.RESTRICTED)
            || (nativeProviders.isEmpty() && skylarkProviders.isEmpty()));

    this.nativeProviders = nativeProviders;
    this.skylarkProviders = skylarkProviders;
}