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.api.codegen.transformer.py.PythonImportSectionTransformer.java

/**
 * For each ProtoFile dependency, put its TypeAlias in allTypeTable; and if it is a local import,
 * then put it in the given localImportNames, otherwise if it is a shared import, but it in the
 * given sharedImportNames.//w w  w. j a  v  a2s .c  o m
 */
private void populateTypeTable(List<ProtoFile> protoFileDependencies, ModelTypeTable allTypeTable,
        Set<String> localImportNames, Set<String> sharedImportNames, String packageName) {
    for (ProtoFile protoFile : protoFileDependencies) {
        // For python, adding a single message from the proto file to the type table will populate
        // the type table with the correct imports.
        ImmutableList<MessageType> messages = protoFile.getMessages();
        if (!messages.isEmpty()) {
            TypeRef typeRef = TypeRef.of(messages.get(0));
            allTypeTable.getAndSaveNicknameFor(typeRef);

            if (protoFile.getFullName().equals(packageName)) {
                localImportNames.add(allTypeTable.getFullNameFor(typeRef));
            } else {
                sharedImportNames.add(allTypeTable.getFullNameFor(typeRef));
            }
        }
    }
}

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

@Override
public Aspect create(ConfiguredTarget base, RuleContext ruleContext, AspectParameters parameters) {
    if (!checkShouldCreateAspect(ruleContext)) {
        return new Aspect.Builder(NAME).build();
    }/*from  w  w  w. ja  v  a  2  s .  com*/

    ProtoSourcesProvider protoSourcesProvider = base.getProvider(ProtoSourcesProvider.class);
    ImmutableList<Artifact> protoSources = protoSourcesProvider.getProtoSources();
    NestedSet<Artifact> transitiveImports = protoSourcesProvider.getTransitiveImports();

    J2ObjcSrcsProvider.Builder srcsBuilder = new J2ObjcSrcsProvider.Builder();
    Iterable<Artifact> headerMappingFiles;
    Iterable<Artifact> classMappingFiles;

    if (protoSources.isEmpty()) {
        headerMappingFiles = ImmutableList.of();
        classMappingFiles = ImmutableList.of();
    } else {
        J2ObjcSource j2ObjcSource = j2ObjcSource(ruleContext, protoSources);
        headerMappingFiles = headerMappingFiles(ruleContext, protoSources);
        classMappingFiles = classMappingFiles(ruleContext, protoSources);
        srcsBuilder.addSource(j2ObjcSource);

        createActions(base, ruleContext, protoSources, transitiveImports, headerMappingFiles, classMappingFiles,
                j2ObjcSource);
    }

    J2ObjcSrcsProvider j2objcSrcsProvider = srcsBuilder.addTransitiveJ2ObjcSrcs(ruleContext, "deps").build();
    NestedSet<Artifact> j2ObjcTransitiveHeaderMappingFiles = j2ObjcTransitiveHeaderMappingFiles(ruleContext,
            headerMappingFiles);
    NestedSet<Artifact> j2ObjcTransitiveClassMappingFiles = j2ObjcTransitiveClassMappingFiles(ruleContext,
            classMappingFiles);

    return new Aspect.Builder(NAME).addProvider(J2ObjcSrcsProvider.class, j2objcSrcsProvider)
            .addProvider(J2ObjcMappingFileProvider.class,
                    new J2ObjcMappingFileProvider(j2ObjcTransitiveHeaderMappingFiles,
                            j2ObjcTransitiveClassMappingFiles,
                            NestedSetBuilder.<Artifact>stableOrder().build()))
            .build();
}

From source file:com.google.walkaround.slob.server.LocalMutationProcessor.java

public void runPreCommit(CheckedTransaction tx, ObjectId slobId, MutationLog.Appender appender)
        throws PermanentFailure, RetryableFailure {
    ImmutableList<Delta<String>> stagedDeltas = ImmutableList.copyOf(appender.getStagedDeltas());
    Preconditions.checkArgument(!stagedDeltas.isEmpty(),
            // TODO(ohler): make this less error-prone.
            "No deltas staged; must call runPreCommit() before appender.finish()");
    for (PreCommitAction action : preCommitActions) {
        log.info("Calling pre-commit action " + action);
        action.run(tx, slobId, stagedDeltas, appender.getStagedVersion(), appender.getStagedState());
    }// w w w  .  j  av  a 2 s  .c  om
}

From source file:com.facebook.buck.cxx.PrebuiltCxxLibraryDescription.java

private static SourcePath getApplicableSourcePath(final BuildTarget target, final CellPathResolver cellRoots,
        final ProjectFilesystem filesystem, final BuildRuleResolver ruleResolver, final CxxPlatform cxxPlatform,
        Optional<String> versionSubDir, final String basePathString, final Optional<String> addedPathString) {
    ImmutableList<BuildRule> deps;
    MacroHandler handler = getMacroHandler(Optional.of(cxxPlatform));
    try {//from   w  ww . ja v  a2  s .c o m
        deps = handler.extractBuildTimeDeps(target, cellRoots, ruleResolver, basePathString);
    } catch (MacroException e) {
        deps = ImmutableList.of();
    }
    Path libDirPath = filesystem
            .getPath(expandMacros(handler, target, cellRoots, ruleResolver, basePathString));

    if (versionSubDir.isPresent()) {
        libDirPath = filesystem.getPath(versionSubDir.get()).resolve(libDirPath);
    }

    // If there are no deps then this is just referencing a path that should already be there
    // So just expand the macros and return a PathSourcePath
    if (deps.isEmpty()) {
        Path resultPath = libDirPath;
        if (addedPathString.isPresent()) {
            resultPath = libDirPath
                    .resolve(expandMacros(handler, target, cellRoots, ruleResolver, addedPathString.get()));
        }
        resultPath = target.getBasePath().resolve(resultPath);
        return new PathSourcePath(filesystem, resultPath);
    }

    // If we get here then this is referencing the output from a build rule.
    // This always return a BuildTargetSourcePath
    Path p = filesystem.resolve(libDirPath);
    if (addedPathString.isPresent()) {
        p = p.resolve(addedPathString.get());
    }
    p = filesystem.relativize(p);
    return new BuildTargetSourcePath(deps.iterator().next().getBuildTarget(), p);
}

From source file:com.addthis.hydra.task.source.bundleizer.RegexBundleizer.java

public RegexBundleizer(@JsonProperty("fields") ImmutableList<AutoField> fields,
        @JsonProperty("regex") Pattern regex) {
    this.regex = regex;
    Map<String, Integer> namedGroups = tryCallNamedGroups(regex);
    if (namedGroups == null) {
        if (estimateIfPatternHasNamedGroups(regex)) {
            throw new IllegalArgumentException("Looks like named groups were used, but we can't support them");
        } else if (fields.isEmpty()) {
            throw new IllegalArgumentException("No fields were specified, and we can't support named groups");
        } else {//from  w  w w .j  a  va 2 s .  co m
            this.fields = fields;
        }
    } else if (fields.isEmpty() == namedGroups.isEmpty()) {
        throw new IllegalArgumentException("Must use (exactly one of) either named groups or fields");
    } else if (!namedGroups.isEmpty()) {
        int maxGroupIndex = namedGroups.values().stream().mapToInt(Integer::intValue).max().getAsInt() - 1;
        AutoField[] fieldsFromGroups = new AutoField[maxGroupIndex + 1];
        Arrays.fill(fieldsFromGroups, new NoopField());
        namedGroups.forEach((key, value) -> fieldsFromGroups[value - 1] = new CachingField(key));
        this.fields = ImmutableList.copyOf(fieldsFromGroups);
    } else {
        this.fields = fields;
    }
}

From source file:com.google.errorprone.bugpatterns.argumentselectiondefects.NamedParameterChecker.java

private Description matchNewClassOrMethodInvocation(MethodSymbol symbol,
        ImmutableList<Commented<ExpressionTree>> arguments, Tree tree, VisitorState state) {

    if (symbol == null) {
        return Description.NO_MATCH;
    }/* w  w w .  jav a2s  .  c o m*/

    boolean commentsRequired = hasRequiresNamedParametersAnnotation().matches(tree, state);

    // if we don't have parameter names available then raise an error if comments required, else
    // silently ignore
    List<VarSymbol> parameters = symbol.getParameters();
    if (containsSyntheticParameterName(parameters)) {
        return commentsRequired ? buildDescription(tree)
                .setMessage("Method requires parameter name comments but parameter names are not available.")
                .build() : Description.NO_MATCH;
    }

    ImmutableList<LabelledArgument> labelledArguments = LabelledArgument.createFromParametersList(parameters,
            arguments);

    ImmutableList<LabelledArgument> incorrectlyLabelledArguments = labelledArguments.stream()
            .filter(labelledArgument -> !labelledArgument.isCorrectlyAnnotated(commentsRequired))
            .collect(toImmutableList());

    if (incorrectlyLabelledArguments.isEmpty()) {
        return Description.NO_MATCH;
    }

    // Build fix
    // In general: if a comment is missing and it should be there then we suggest adding it
    // If a comment is wrong but matches the parameter name of a different argument then we suggest
    // swapping the arguments. If a comment is wrong and matches nothing then we suggest changing it

    SuggestedFix.Builder fixBuilder = SuggestedFix.builder();
    for (LabelledArgument argumentWithBadLabel : incorrectlyLabelledArguments) {
        switch (argumentWithBadLabel.match()) {
        case NOT_ANNOTATED:
            fixBuilder.prefixWith(argumentWithBadLabel.actualParameter().tree(),
                    NamedParameterComment.toCommentText(argumentWithBadLabel.parameterName()));
            break;
        case BAD_MATCH:
        case APPROXIMATE_MATCH:
            // we know that this has a comment because it was a bad match
            Comment badLabel = argumentWithBadLabel.label().get();
            Optional<LabelledArgument> maybeGoodTarget = findGoodSwap(argumentWithBadLabel, labelledArguments);

            if (maybeGoodTarget.isPresent()) {
                LabelledArgument argumentWithCorrectLabel = maybeGoodTarget.get();
                fixBuilder.swap(argumentWithBadLabel.actualParameter().tree(),
                        argumentWithCorrectLabel.actualParameter().tree());

                Optional<Comment> correctLabel = argumentWithCorrectLabel.label();
                if (correctLabel.isPresent()) {
                    replaceComment(badLabel, correctLabel.get().getText(), fixBuilder);
                } else {
                    replaceComment(badLabel, "", fixBuilder);
                    fixBuilder.prefixWith(argumentWithCorrectLabel.actualParameter().tree(),
                            NamedParameterComment.toCommentText(argumentWithCorrectLabel.parameterName()));
                }
            } else {
                // there were no matches so maybe the comment is wrong - suggest a fix to change it
                replaceComment(badLabel,
                        NamedParameterComment.toCommentText(argumentWithBadLabel.parameterName()), fixBuilder);
            }
            break;
        case EXACT_MATCH:
            throw new IllegalArgumentException("There should be no good matches in the list of bad matches");
        }
    }

    return buildDescription(tree)
            .setMessage("Parameters with incorrectly labelled arguments: " + incorrectlyLabelledArguments
                    .stream().map(NamedParameterChecker::describeIncorrectlyLabelledArgument)
                    .collect(Collectors.joining(", ")))
            .addFix(fixBuilder.build()).build();
}

From source file:com.google.errorprone.bugpatterns.CatchFail.java

@Override
public Description matchTry(TryTree tree, VisitorState state) {
    if (tree.getCatches().isEmpty()) {
        return NO_MATCH;
    }/*from ww  w  .  j a  v  a 2s  .c o  m*/
    // Find catch blocks that contain only a call to fail, and that ignore the caught exception.
    ImmutableList<CatchTree> catchBlocks = tree.getCatches().stream()
            .filter(c -> c.getBlock().getStatements().size() == 1
                    && FAIL_METHOD.matches(getOnlyElement(c.getBlock().getStatements()), state))
            .filter(c -> !catchVariableIsUsed(c)).collect(toImmutableList());
    if (catchBlocks.isEmpty()) {
        return NO_MATCH;
    }
    Description.Builder description = buildDescription(tree);
    rethrowFix(catchBlocks, state).ifPresent(description::addFix);
    deleteFix(tree, catchBlocks, state).ifPresent(description::addFix);
    return description.build();
}

From source file:org.jclouds.googlecloudstorage.blobstore.GoogleCloudStorageBlobStore.java

@Override
public String completeMultipartUpload(MultipartUpload mpu, List<MultipartPart> parts) {
    ImmutableList.Builder<GoogleCloudStorageObject> objectsBuilder = ImmutableList.builder();
    for (MultipartPart part : parts) {
        objectsBuilder.add(api.getObjectApi().getObject(mpu.containerName(),
                Strings2.urlEncode(getMPUPartName(mpu, part.partNumber()))));
    }//from ww  w .j  a v a 2 s . c  o m

    ObjectTemplate destination = blobMetadataToObjectTemplate.apply(mpu.blobMetadata());
    final ImmutableList<GoogleCloudStorageObject> objects = objectsBuilder.build();
    if (!objects.isEmpty()) {
        destination.storageClass(objects.get(0).storageClass());
    }
    if (mpu.putOptions().getBlobAccess() == BlobAccess.PUBLIC_READ) {
        ObjectAccessControls controls = ObjectAccessControls.builder().entity("allUsers")
                .bucket(mpu.containerName()).role(READER).build();
        destination.addAcl(controls);
    }

    ComposeObjectTemplate template = ComposeObjectTemplate.builder().fromGoogleCloudStorageObject(objects)
            .destination(destination).build();
    String eTag = api.getObjectApi()
            .composeObjects(mpu.containerName(), Strings2.urlEncode(mpu.blobName()), template).etag();

    // remove parts, composite object keeps a reference to them
    ImmutableList.Builder<String> builder = ImmutableList.builder();
    for (MultipartPart part : parts) {
        builder.add(getMPUPartName(mpu, part.partNumber()));
    }
    removeBlobs(mpu.containerName(), builder.build());

    return eTag;
}

From source file:com.facebook.buck.rules.modern.Serializer.java

/** See Serialize(T instance) above. */
public <T extends AddsToRuleKey> Either<HashCode, byte[]> serialize(T instance, ClassInfo<T> classInfo)
        throws IOException {
    if (cache.containsKey(instance)) {
        return Objects.requireNonNull(cache.get(instance));
    }/*w w w.j a v  a2  s. c  o m*/
    Visitor visitor = new Visitor(instance.getClass());

    Optional<CustomClassBehaviorTag> serializerTag = CustomBehaviorUtils.getBehavior(instance.getClass(),
            CustomClassSerialization.class);
    if (serializerTag.isPresent()) {
        @SuppressWarnings("unchecked")
        CustomClassSerialization<T> customSerializer = (CustomClassSerialization<T>) serializerTag.get();
        customSerializer.serialize(instance, visitor);
    } else {
        classInfo.visit(instance, visitor);
    }

    return Objects.requireNonNull(cache.computeIfAbsent(instance, ignored -> {
        byte[] data = visitor.byteStream.toByteArray();
        ImmutableList<HashCode> children = visitor.children.build().distinct()
                .collect(ImmutableList.toImmutableList());
        return data.length < MAX_INLINE_LENGTH && children.isEmpty() ? Either.ofRight(data)
                : Either.ofLeft(registerNewValue(instance, data, children));
    }));
}

From source file:org.apache.rya.indexing.entity.storage.mongo.MongoEntityStorage.java

/**
 * Searches the Entity storage for all Entities that contain all the
 * specified explicit type IDs./*from   w  w w  .j  a va  2 s  . c o  m*/
 * @param explicitTypeIds the {@link ImmutableList} of {@link RyaURI}s that
 * are being searched for.
 * @return the {@link List} of {@link Entity}s that have all the specified
 * explicit type IDs. If nothing was found an empty {@link List} is
 * returned.
 * @throws EntityStorageException
 */
private List<Entity> searchHasAllExplicitTypes(final ImmutableList<RyaURI> explicitTypeIds)
        throws EntityStorageException {
    final List<Entity> hasAllExplicitTypesEntities = new ArrayList<>();
    if (!explicitTypeIds.isEmpty()) {
        // Grab the first type from the explicit type IDs.
        final RyaURI firstType = explicitTypeIds.get(0);

        // Check if that type exists anywhere in storage.
        final List<RyaURI> subjects = new ArrayList<>();
        Optional<Type> type;
        try {
            if (mongoTypeStorage == null) {
                mongoTypeStorage = new MongoTypeStorage(mongo, ryaInstanceName);
            }
            type = mongoTypeStorage.get(firstType);
        } catch (final TypeStorageException e) {
            throw new EntityStorageException("Unable to get entity type: " + firstType, e);
        }
        if (type.isPresent()) {
            // Grab the subjects for all the types we found matching "firstType"
            final ConvertingCursor<TypedEntity> cursor = search(Optional.empty(), type.get(),
                    Collections.emptySet());
            while (cursor.hasNext()) {
                final TypedEntity typedEntity = cursor.next();
                final RyaURI subject = typedEntity.getSubject();
                subjects.add(subject);
            }
        }

        // Now grab all the Entities that have the subjects we found.
        for (final RyaURI subject : subjects) {
            final Optional<Entity> entityFromSubject = get(subject);
            if (entityFromSubject.isPresent()) {
                final Entity candidateEntity = entityFromSubject.get();
                // Filter out any entities that don't have all the same
                // types associated with them as our original list of
                // explicit type IDs. We already know the entities we found
                // have "firstType" but now we have access to all the other
                // types they have.
                if (candidateEntity.getExplicitTypeIds().containsAll(explicitTypeIds)) {
                    hasAllExplicitTypesEntities.add(candidateEntity);
                }
            }
        }
    }

    return hasAllExplicitTypesEntities;
}