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.spectralogic.dsbrowser.gui.services.tasks.Ds3PutJob.java

@Override
public void executeJob() throws Exception {
    final boolean metadata = settings.getFilePropertiesSettings().isFilePropertiesEnabled();
    final boolean hasPriority = !Guard.isStringNullOrEmpty(jobPriority);
    final Instant jobStartInstant = Instant.now();
    final String startJobDate = dateTimeUtils.nowAsString();
    final String jobInitiateTitleMessage = buildJobInitiatedTitleMessage(startJobDate, ds3Client);
    final String transferringMessage = buildTransferringMessage(resourceBundle);

    LOG.info(resourceBundle.getString("putJobStarted"));
    updateTitle(resourceBundle.getString("blackPearlHealth"));

    if (!CheckNetwork.isReachable(ds3Client)) {
        hostNotAvailable();//from   w w  w  .  j a v  a2  s .  com
        return;
    }
    updateTitle(jobInitiateTitleMessage);
    updateMessage(transferringMessage);

    final ImmutableMap.Builder<String, Path> fileMapBuilder = ImmutableMap.builder();
    final ImmutableMap.Builder<String, Path> folderMapBuilder = ImmutableMap.builder();
    final ImmutableMap.Builder<String, Path> fileMapperBuilder = ImmutableMap.builder();
    files.forEach(
            pair -> buildMaps(fileMapBuilder, folderMapBuilder, pair, loggingService, targetDir, delimiter));
    final ImmutableMap<String, Path> fileMap = fileMapBuilder.build();
    final ImmutableMap<String, Path> folderMap = folderMapBuilder.build();
    fileMapperBuilder.putAll(fileMap);
    fileMapperBuilder.putAll(folderMap);
    final ImmutableMap<String, Path> fileMapper = fileMapperBuilder.build();
    final ImmutableList<Ds3Object> objects = fileMapper.entrySet().stream().map(this::buildDs3Object)
            .filter(Optional::isPresent).map(Optional::get).collect(GuavaCollectors.immutableList());
    if (objects.isEmpty()) {
        loggingService.logMessage("Job was empty, not sending", LogType.INFO);
        return;
    }
    this.job = Ds3ClientHelpers.wrap(ds3Client).startWriteJob(bucket, objects);
    final long totalJobSize = getTotalJobSize();

    job.withMaxParallelRequests(maximumNumberOfParallelThreads);

    ParseJobInterruptionMap.saveValuesToFiles(jobInterruptionStore, fileMap, folderMap,
            ds3Client.getConnectionDetails().getEndpoint(), this.getJobId(), totalJobSize, targetDir,
            dateTimeUtils, PUT, bucket);

    updateMessage(StringBuilderUtil
            .transferringTotalJobString(FileSizeFormat.getFileSizeType(totalJobSize), targetDirectory)
            .toString());

    if (hasPriority) {
        ds3Client.modifyJobSpectraS3(
                new ModifyJobSpectraS3Request(job.getJobId()).withPriority(Priority.valueOf(jobPriority)));
    }

    if (metadata) {
        LOG.info("Registering metadata access Implementation");
        job.withMetadata(new MetadataAccessImpl(fileMapper));
    }

    addWaitingForChunkListener(totalJobSize, bucket + StringConstants.DOUBLE_SLASH + targetDir);
    final AtomicLong totalSent = addDataTransferListener(totalJobSize);
    job.attachObjectCompletedListener(
            obj -> updateGuiOnComplete(startJobDate, jobStartInstant, totalJobSize, totalSent, obj));

    job.transfer(file -> FileChannel.open(PathUtil.resolveForSymbolic(fileMapper.get(file)),
            StandardOpenOption.READ));

    final Disposable d = waitForPermanentStorageTransfer(totalJobSize).observeOn(JavaFxScheduler.platform())
            .doOnComplete(() -> {
                LOG.info("Job transferred to permanent storage location");

                final String newDate = dateTimeUtils.nowAsString();
                loggingService
                        .logMessage(StringBuilderUtil
                                .jobSuccessfullyTransferredString(PUT,
                                        FileSizeFormat.getFileSizeType(totalJobSize), bucket + "\\" + targetDir,
                                        newDate, resourceBundle.getString("permanentStorageLocation"), false)
                                .toString(), LogType.SUCCESS);

                Ds3PanelService.throttledRefresh(remoteDestination);
                ParseJobInterruptionMap.removeJobID(jobInterruptionStore, this.getJobId().toString(),
                        ds3Client.getConnectionDetails().getEndpoint(), deepStorageBrowserPresenter,
                        loggingService);
            }).subscribe();
    while (!d.isDisposed()) {
        Thread.sleep(1000);
    }
}

From source file:com.facebook.buck.artifact_cache.config.ArtifactCacheBuckConfig.java

private ImmutableSet<DirCacheEntry> getDirCacheEntries() {
    ImmutableSet.Builder<DirCacheEntry> result = ImmutableSet.builder();

    ImmutableList<String> names = getDirCacheNames();
    boolean implicitLegacyCache = names.isEmpty() && getArtifactCacheModes().contains(ArtifactCacheMode.dir);
    if (implicitLegacyCache || legacyDirCacheConfigurationFieldsPresent()) {
        result.add(obtainDirEntryForName(Optional.empty()));
    }//  w w  w.  ja  v  a  2  s  . c om

    for (String cacheName : names) {
        result.add(obtainDirEntryForName(Optional.of(cacheName)));
    }

    return result.build();
}

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

/**
 * Validates the proto attributes for this target.
 *
 * <ul>//w  ww  .j av  a2s. c om
 * <li>Validates that there are protos specified to be compiled.
 * <li>Validates that, when enabling the open source protobuf library, the options for the PB2 are
 *     not specified also.
 * <li>Validates that, when enabling the open source protobuf library, the rule specifies at least
 *     one portable proto filter file.
 * </ul>
 */
public void validate() throws RuleErrorException {
    PrerequisiteArtifacts prerequisiteArtifacts = ruleContext.getPrerequisiteArtifacts("deps", Mode.TARGET);
    ImmutableList<Artifact> protos = prerequisiteArtifacts.filter(FileType.of(".proto")).list();

    if (ruleContext.attributes()
            .isAttributeValueExplicitlySpecified(ObjcProtoLibraryRule.PORTABLE_PROTO_FILTERS_ATTR)) {
        if (!protos.isEmpty()) {
            ruleContext.throwWithAttributeError("deps", FILES_NOT_ALLOWED_ERROR);
        }
        if (getProtoFiles().isEmpty() && !hasObjcProtoLibraryDependencies()) {
            ruleContext.throwWithRuleError(NO_PROTOS_ERROR);
        }

        if (getPortableProtoFilters().isEmpty()) {
            ruleContext.throwWithRuleError(PORTABLE_PROTO_FILTERS_EMPTY_ERROR);
        }

        if (usesObjcHeaderNames() || needsPerProtoIncludes() || getOptionsFile().isPresent()) {
            ruleContext.throwWithRuleError(PORTABLE_PROTO_FILTERS_NOT_EXCLUSIVE_ERROR);
        }
        if (hasPB2Dependencies()) {
            ruleContext.throwWithRuleError(PROTOCOL_BUFFERS2_IN_PROTOBUF_DEPS_ERROR);
        }

    } else {
        if (!protos.isEmpty()) {
            ruleContext.attributeWarning("deps", FILES_DEPRECATED_WARNING);
        }
        if (getProtoFiles().isEmpty()) {
            ruleContext.throwWithRuleError(NO_PROTOS_ERROR);
        }

        if (!usesObjcHeaderNames()) {
            ruleContext.ruleWarning("As part of the migration process, it is recommended to enable "
                    + "use_objc_header_names. Please refer to b/29368416 for more information.");
        }
        if (hasObjcProtoLibraryDependencies()) {
            ruleContext.throwWithRuleError(OBJC_PROTO_LIB_DEP_IN_PROTOCOL_BUFFERS2_DEPS_ERROR);
        }
    }
}

From source file:com.netflix.metacat.hive.connector.HiveDetailMetadata.java

private void updateTable(final Table table, final ConnectorSession session,
        final ConnectorTableDetailMetadata tableDetailMetadata) {
    if (table.getParameters() == null) {
        table.setParameters(Maps.newHashMap());
    }//from   ww w .  ja  v a2s  . co m
    table.getParameters().putIfAbsent(PARAMETER_EXTERNAL, "TRUE");
    if (tableDetailMetadata.getMetadata() != null) {
        table.getParameters().putAll(tableDetailMetadata.getMetadata());
    }

    //storage
    final StorageDescriptor sd = table.getSd() != null ? table.getSd() : new StorageDescriptor();
    String inputFormat = null;
    String outputFormat = null;
    Map<String, String> sdParameters = Maps.newHashMap();
    final String location = tableDetailMetadata.getStorageInfo() == null ? null
            : tableDetailMetadata.getStorageInfo().getUri();
    if (location != null) {
        sd.setLocation(location);
    } else if (sd.getLocation() == null) {
        final String locationStr = getDatabase(tableDetailMetadata.getTable().getSchemaName()).getLocationUri();
        final Path databasePath = new Path(locationStr);
        final Path targetPath = new Path(databasePath, tableDetailMetadata.getTable().getTableName());
        sd.setLocation(targetPath.toString());
    }

    SerDeInfo serdeInfo = sd.getSerdeInfo();
    final StorageInfo storageInfo = tableDetailMetadata.getStorageInfo();
    if (serdeInfo != null) {
        serdeInfo.setName(tableDetailMetadata.getTable().getTableName());
        if (storageInfo != null) {
            if (!Strings.isNullOrEmpty(storageInfo.getSerializationLib())) {
                serdeInfo.setSerializationLib(storageInfo.getSerializationLib());
            }
            if (storageInfo.getSerdeInfoParameters() != null
                    && !storageInfo.getSerdeInfoParameters().isEmpty()) {
                serdeInfo.setParameters(storageInfo.getSerdeInfoParameters());
            }
            inputFormat = storageInfo.getInputFormat();
            outputFormat = storageInfo.getOutputFormat();
            if (storageInfo.getParameters() != null && !storageInfo.getParameters().isEmpty()) {
                sdParameters = storageInfo.getParameters();
            }
        }
    } else {
        serdeInfo = new SerDeInfo();
        serdeInfo.setName(tableDetailMetadata.getTable().getTableName());
        if (storageInfo != null) {
            serdeInfo.setSerializationLib(storageInfo.getSerializationLib());
            if (storageInfo.getSerdeInfoParameters() != null
                    && !storageInfo.getSerdeInfoParameters().isEmpty()) {
                serdeInfo.setParameters(storageInfo.getSerdeInfoParameters());
            }
            inputFormat = storageInfo.getInputFormat();
            outputFormat = storageInfo.getOutputFormat();
            if (storageInfo.getParameters() != null && !storageInfo.getParameters().isEmpty()) {
                sdParameters = storageInfo.getParameters();
            }
        } else {
            final HiveStorageFormat hiveStorageFormat = extractHiveStorageFormat(table);
            serdeInfo.setSerializationLib(hiveStorageFormat.getSerDe());
            serdeInfo.setParameters(ImmutableMap.<String, String>of());
            inputFormat = hiveStorageFormat.getInputFormat();
            outputFormat = hiveStorageFormat.getOutputFormat();
        }
        sd.setSerdeInfo(serdeInfo);
    }

    final ImmutableList.Builder<FieldSchema> columnsBuilder = ImmutableList.builder();
    final ImmutableList.Builder<FieldSchema> partitionKeysBuilder = ImmutableList.builder();
    for (ColumnMetadata column : tableDetailMetadata.getColumns()) {
        final FieldSchema field = converterUtil.toFieldSchema(column);
        if (column.isPartitionKey()) {
            partitionKeysBuilder.add(field);
        } else {
            columnsBuilder.add(field);
        }
    }
    final ImmutableList<FieldSchema> columns = columnsBuilder.build();
    if (!columns.isEmpty()) {
        sd.setCols(columns);
    }
    if (!Strings.isNullOrEmpty(inputFormat)) {
        sd.setInputFormat(inputFormat);
    }
    if (!Strings.isNullOrEmpty(outputFormat)) {
        sd.setOutputFormat(outputFormat);
    }
    if (sd.getParameters() == null) {
        sd.setParameters(sdParameters);
    }

    //partition keys
    final ImmutableList<FieldSchema> partitionKeys = partitionKeysBuilder.build();
    if (!partitionKeys.isEmpty()) {
        table.setPartitionKeys(partitionKeys);
    }
    table.setSd(sd);
}

From source file:org.ow2.authzforce.core.pdp.impl.ModularAttributeProvider.java

/** {@inheritDoc} */
@Override/*from  w  w  w  .  ja va  2  s .c  o  m*/
public final <AV extends AttributeValue> AttributeBag<AV> get(final AttributeFqn attributeFqn,
        final Datatype<AV> datatype, final EvaluationContext context) throws IndeterminateEvaluationException {
    try {
        final AttributeBag<AV> contextBag = context.getNamedAttributeValue(attributeFqn, datatype);
        if (contextBag != null) {
            LOGGER.debug("Values of attribute {}, type={} found in evaluation context: {}", attributeFqn,
                    datatype, contextBag);
            return contextBag;
        }

        // else attribute not found in context, ask the Provider modules, if any
        LOGGER.debug("Requesting attribute {} from Provider modules (by provided attribute ID): {}",
                attributeFqn, designatorModsByAttrId);
        final ImmutableList<NamedAttributeProvider> attrProviders = designatorModsByAttrId.get(attributeFqn);
        /*
         * According to doc, a non-null empty list is returned if no mappings
         */
        assert attrProviders != null;
        if (attrProviders.isEmpty()) {
            LOGGER.debug(
                    "No value found for required attribute {}, type={} in evaluation context and not supported by any Attribute Provider module",
                    attributeFqn, datatype);
            throw new IndeterminateEvaluationException(
                    "Not in context and no Attribute Provider module supporting requested attribute: "
                            + attributeFqn,
                    XacmlStatusCode.MISSING_ATTRIBUTE.value());
        }

        AttributeBag<AV> result = null;
        /*
         * Try all modules supporting this attribute until value found
         */
        for (final NamedAttributeProvider attrProvider : attrProviders) {
            result = attrProvider.get(attributeFqn, datatype, context);
            if (result != null && !result.isEmpty()) {
                break;
            }
        }

        if (result == null) {
            /*
             * If no attribute provider can provide the attribute, it is as if it was a request attribute with no value, therefore implicitly setting AttributeSource to REQUEST.
             */
            result = Bags.emptyAttributeBag(datatype,
                    INDETERMINATE_EXCEPTION_NO_VALUE_FROM_ATTRIBUTE_PROVIDERS);
        }

        /*
         * Cache the attribute value(s) in context to avoid waste of time querying the module twice for same attribute
         */
        context.putNamedAttributeValueIfAbsent(attributeFqn, result);
        LOGGER.debug(
                "Values of attribute {}, type={} returned by attribute Provider module #{} (cached in context): {}",
                attributeFqn, datatype, attrProviders, result);
        issuedToNonIssuedAttributeCopyMode.process(attributeFqn, result, context);
        return result;
    } catch (final IndeterminateEvaluationException e) {
        /*
         * This error does not necessarily matter, it depends on whether the attribute is required, i.e. MustBePresent=true for AttributeDesignator/Selector So we let
         * AttributeDesignator/Select#evaluate() method log the errors if MustBePresent=true. Here debug level is enough
         */
        LOGGER.debug("Error finding attribute {}, type={}", attributeFqn, datatype, e);

        /**
         * If error occurred, we put the empty value to prevent retry in the same context, which may succeed at another time in the same context, resulting in different value of the same attribute
         * at different times during evaluation within the same context, therefore inconsistencies. The value(s) must remain constant during the evaluation context, as explained in section 7.3.5
         * Attribute Retrieval of XACML core spec:
         * <p>
         * Regardless of any dynamic modifications of the request context during policy evaluation, the PDP SHALL behave as if each bag of attribute values is fully populated in the context before
         * it is first tested, and is thereafter immutable during evaluation. (That is, every subsequent test of that attribute shall use 3313 the same bag of values that was initially tested.)
         * </p>
         * Therefore, if no value found, we keep it that way until evaluation is done for the current request context.
         * <p>
         * We could put the null value to indicate the evaluation error, instead of an empty Bag, but it would make the result of the code used at the start of this method ambiguous/confusing:
         * <p>
         * <code>
         * final Bag<T> contextBag = context.getAttributeDesignatorResult(AttributeFqn,...)
         * </code>
         * </p>
         * <p>
         * Indeed, contextBag could be null for one of these two reasons:
         * <ol>
         * <li>The attribute ('attributeFqn') has never been requested in this context;
         * <li>It has been requested before in this context but could not be found: error occurred (IndeterminateEvaluationException)</li>
         * </ol>
         * To avoid this confusion, we put an empty Bag (with some error info saying why this is empty).
         * </p>
         */
        final AttributeBag<AV> result = Bags.emptyAttributeBag(datatype, e);
        /*
         * NOTE: It might happen - e.g. in conformance test IIB033 (Request's resource-id attribute datatype is different from datatype used in Policy) - that
         * context.getAttributeDesignatorResult(AttributeFqn, bagDatatype) threw IndeterminateEvaluationException although a value for 'attributeFqn' exists in context, because the existing
         * datatype is different from requested 'bagDatatype'. In this case, the call below will return false (the value should not be overridden). We don't care about the result; what matters is
         * that the value is set to an empty bag if there was no value.
         */
        context.putNamedAttributeValueIfAbsent(attributeFqn, result);
        return result;
    } catch (final UnsupportedOperationException e) {
        /*
         * Should not happen, this is highly unexpected and should be considered a fatal error (it means the AttributeProvider does not respect its contract)
         */
        throw new RuntimeException(
                "Inconsistent AttributeProvider: throwing UnsupportedOperationException for an attribute (name="
                        + attributeFqn + ", type=" + datatype
                        + ") that should be supported according to the provider's contract (getProvidedAttributes() result) ",
                e);
    }
}

From source file:org.gradle.model.internal.manage.schema.extract.ManagedImplTypeSchemaExtractionStrategySupport.java

public <R> ModelSchemaExtractionResult<R> extract(final ModelSchemaExtractionContext<R> extractionContext,
        ModelSchemaStore store, final ModelSchemaCache cache) {
    ModelType<R> type = extractionContext.getType();
    Class<? super R> clazz = type.getRawClass();
    if (isTarget(type)) {
        validateType(type, extractionContext);

        Iterable<Method> methods = Arrays.asList(clazz.getMethods());
        if (!clazz.isInterface()) {
            methods = filterIgnoredMethods(methods);
        }/*from  w w  w . j  a va 2s .  c  o  m*/
        ImmutableListMultimap<String, Method> methodsByName = Multimaps.index(methods,
                new Function<Method, String>() {
                    public String apply(Method method) {
                        return method.getName();
                    }
                });

        ensureNoOverloadedMethods(extractionContext, methodsByName);

        List<ModelProperty<?>> properties = Lists.newLinkedList();
        List<Method> handled = Lists.newArrayListWithCapacity(clazz.getMethods().length);
        ReturnTypeSpecializationOrdering returnTypeSpecializationOrdering = new ReturnTypeSpecializationOrdering();

        for (String methodName : methodsByName.keySet()) {
            if (methodName.startsWith("get") && !methodName.equals("get")) {
                ImmutableList<Method> getterMethods = methodsByName.get(methodName);

                // The overload check earlier verified that all methods for are equivalent for our purposes
                // So, taking the first one with the most specialized return type is fine.
                Method sampleMethod = returnTypeSpecializationOrdering.max(getterMethods);

                boolean abstractGetter = Modifier.isAbstract(sampleMethod.getModifiers());

                if (sampleMethod.getParameterTypes().length != 0) {
                    throw invalidMethod(extractionContext, "getter methods cannot take parameters",
                            sampleMethod);
                }

                Character getterPropertyNameFirstChar = methodName.charAt(3);
                if (!Character.isUpperCase(getterPropertyNameFirstChar)) {
                    throw invalidMethod(extractionContext,
                            "the 4th character of the getter method name must be an uppercase character",
                            sampleMethod);
                }

                ModelType<?> returnType = ModelType.returnType(sampleMethod);

                String propertyNameCapitalized = methodName.substring(3);
                String propertyName = StringUtils.uncapitalize(propertyNameCapitalized);
                String setterName = "set" + propertyNameCapitalized;
                ImmutableList<Method> setterMethods = methodsByName.get(setterName);

                boolean isWritable = !setterMethods.isEmpty();
                if (isWritable) {
                    Method setter = setterMethods.get(0);

                    if (!abstractGetter) {
                        throw invalidMethod(extractionContext,
                                "setters are not allowed for non-abstract getters", setter);
                    }
                    validateSetter(extractionContext, returnType, setter);
                    handled.addAll(setterMethods);
                }

                if (abstractGetter) {
                    ImmutableSet<ModelType<?>> declaringClasses = ImmutableSet
                            .copyOf(Iterables.transform(getterMethods, new Function<Method, ModelType<?>>() {
                                public ModelType<?> apply(Method input) {
                                    return ModelType.of(input.getDeclaringClass());
                                }
                            }));

                    boolean unmanaged = Iterables.any(getterMethods, new Predicate<Method>() {
                        public boolean apply(Method input) {
                            return input.getAnnotation(Unmanaged.class) != null;
                        }
                    });

                    properties.add(ModelProperty.of(returnType, propertyName, isWritable, declaringClasses,
                            unmanaged));
                }
                handled.addAll(getterMethods);
            }
        }

        Iterable<Method> notHandled = Iterables.filter(methodsByName.values(),
                Predicates.not(Predicates.in(handled)));

        // TODO - should call out valid getters without setters
        if (!Iterables.isEmpty(notHandled)) {
            throw invalidMethods(extractionContext, "only paired getter/setter methods are supported",
                    notHandled);
        }

        Class<R> concreteClass = type.getConcreteClass();
        final ModelSchema<R> schema = createSchema(extractionContext, store, type, properties, concreteClass);
        Iterable<ModelSchemaExtractionContext<?>> propertyDependencies = Iterables.transform(properties,
                new Function<ModelProperty<?>, ModelSchemaExtractionContext<?>>() {
                    public ModelSchemaExtractionContext<?> apply(final ModelProperty<?> property) {
                        return toPropertyExtractionContext(extractionContext, property, cache);
                    }
                });

        return new ModelSchemaExtractionResult<R>(schema, propertyDependencies);
    } else {
        return null;
    }
}

From source file:com.google.testing.compile.CompilationSubject.java

private DiagnosticInFile hadDiagnosticContainingMatch(String verb, final Pattern expectedPattern,
        Diagnostic.Kind kind, Diagnostic.Kind... more) {
    ImmutableList<Diagnostic<? extends JavaFileObject>> diagnosticsOfKind = actual().diagnosticsOfKind(kind,
            more);//from www.  j  av  a 2s .c o m
    ImmutableList<Diagnostic<? extends JavaFileObject>> diagnosticsWithMessage = diagnosticsOfKind.stream()
            .filter(diagnostic -> expectedPattern.matcher(diagnostic.getMessage(null)).find())
            .collect(toImmutableList());
    if (diagnosticsWithMessage.isEmpty()) {
        failureStrategy.fail(messageListing(diagnosticsOfKind, "Expected %s %s, but only found:",
                kindToString(kind, false), verb));
    }
    return new DiagnosticInFile(kind, diagnosticsWithMessage);
}

From source file:com.amazonaws.services.kinesis.stormspout.state.zookeeper.ZookeeperStateManager.java

private void bootstrapStateFromZookeeper() {
    ImmutableList<String> shardAssignment = getShardAssignment();
    ImmutableList<IShardGetter> getters;

    // Task could not get an assignment (e.g. there are too many tasks for too few shards).
    if (shardAssignment.isEmpty()) {
        shardStates = new HashMap<>();
        getters = ImmutableList.of();// w  w  w  . j  a  v a 2 s.co m
    } else {
        updateLocalState(shardAssignment);
        getters = makeGetters(shardAssignment);
    }

    this.currentGetter = Iterators.cycle(getters);
    LOG.info(this + " got getter assignment. Handling " + getters + ".");
}

From source file:com.twitter.common.args.ArgScanner.java

private void printHelp(Verifiers verifiers, ArgsInfo argsInfo) {
    ImmutableList.Builder<String> requiredHelps = ImmutableList.builder();
    ImmutableList.Builder<String> optionalHelps = ImmutableList.builder();
    Optional<String> firstArgFileArgumentName = Optional.absent();
    for (OptionInfo<?> optionInfo : ORDER_BY_NAME.immutableSortedCopy(argsInfo.getOptionInfos())) {
        Arg<?> arg = optionInfo.getArg();
        Object defaultValue = arg.uncheckedGet();
        ImmutableList<String> constraints = optionInfo.collectConstraints(verifiers);
        String help = formatHelp(optionInfo, constraints, defaultValue);
        if (!arg.hasDefault()) {
            requiredHelps.add(help);//from   w  w w.ja v a 2  s  .c o  m
        } else {
            optionalHelps.add(help);
        }
        if (optionInfo.argFile() && !firstArgFileArgumentName.isPresent()) {
            firstArgFileArgumentName = Optional.of(optionInfo.getName());
        }
    }

    infoLog("-------------------------------------------------------------------------");
    infoLog(String.format("%s to print this help message",
            Joiner.on(" or ").join(Iterables.transform(ArgumentInfo.HELP_ARGS, ARG_NAME_TO_FLAG))));
    Optional<? extends PositionalInfo<?>> positionalInfoOptional = argsInfo.getPositionalInfo();
    if (positionalInfoOptional.isPresent()) {
        infoLog("\nPositional args:");
        PositionalInfo<?> positionalInfo = positionalInfoOptional.get();
        Arg<?> arg = positionalInfo.getArg();
        Object defaultValue = arg.uncheckedGet();
        ImmutableList<String> constraints = positionalInfo.collectConstraints(verifiers);
        infoLog(String.format("%s%s\n\t%s\n\t(%s)", defaultValue != null ? "default " + defaultValue : "",
                Iterables.isEmpty(constraints) ? "" : " [" + Joiner.on(", ").join(constraints) + "]",
                positionalInfo.getHelp(), positionalInfo.getCanonicalName()));
        // TODO: https://github.com/twitter/commons/issues/353, in the future we may
        // want to support @argfile format for positional arguments. We should check
        // to update firstArgFileArgumentName for them as well.
    }
    ImmutableList<String> required = requiredHelps.build();
    if (!required.isEmpty()) {
        infoLog("\nRequired flags:"); // yes - this should actually throw!
        infoLog(Joiner.on('\n').join(required));
    }
    ImmutableList<String> optional = optionalHelps.build();
    if (!optional.isEmpty()) {
        infoLog("\nOptional flags:");
        infoLog(Joiner.on('\n').join(optional));
    }
    if (firstArgFileArgumentName.isPresent()) {
        infoLog(String.format(
                "\n" + "For arguments that support @argfile format: @argfile is a text file that contains "
                        + "cmdline argument values. For example: -%s=@/tmp/%s_value.txt. The format "
                        + "of the argfile content should be exactly the same as it would be specified on the "
                        + "cmdline.",
                firstArgFileArgumentName.get(), firstArgFileArgumentName.get()));
    }
    infoLog("-------------------------------------------------------------------------");
}

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

/**
 * Adds command-line options for a static library or non-library input into options.
 *
 * @param librariesToLink - a collection that will be exposed as a build variable.
 *//* w  w  w. java  2  s .c om*/
private void addStaticInputLinkOptions(LinkerInput input, SequenceBuilder librariesToLink,
        ImmutableSet.Builder<LinkerInput> expandedLinkerInputsBuilder) {
    ArtifactCategory artifactCategory = input.getArtifactCategory();
    Preconditions.checkArgument(artifactCategory.equals(ArtifactCategory.OBJECT_FILE)
            || artifactCategory.equals(ArtifactCategory.STATIC_LIBRARY)
            || artifactCategory.equals(ArtifactCategory.ALWAYSLINK_STATIC_LIBRARY));
    boolean isAlwaysLinkStaticLibrary = artifactCategory == ArtifactCategory.ALWAYSLINK_STATIC_LIBRARY;

    // input.disableWholeArchive() should only be true for libstdc++/libc++ etc.
    boolean inputIsWholeArchive = !input.disableWholeArchive()
            && (isAlwaysLinkStaticLibrary || needWholeArchive);

    // If we had any LTO artifacts, ltoMap whould be non-null. In that case,
    // we should have created a thinltoParamFile which the LTO indexing
    // step will populate with the exec paths that correspond to the LTO
    // artifacts that the linker decided to include based on symbol resolution.
    // Those files will be included directly in the link (and not wrapped
    // in --start-lib/--end-lib) to ensure consistency between the two link
    // steps.
    Preconditions.checkState(ltoMap == null || thinltoParamFile != null || !allowLtoIndexing);

    // start-lib/end-lib library: adds its input object files.
    if (Link.useStartEndLib(input, CppHelper.getArchiveType(cppConfiguration, ccToolchainProvider))) {
        Iterable<Artifact> archiveMembers = input.getObjectFiles();
        if (!Iterables.isEmpty(archiveMembers)) {
            ImmutableList.Builder<Artifact> nonLtoArchiveMembersBuilder = ImmutableList.builder();
            for (Artifact member : archiveMembers) {
                Artifact a;
                if (ltoMap != null && (a = ltoMap.remove(member)) != null) {
                    // When ltoMap is non-null the backend artifact may be missing due to libraries that
                    // list .o files explicitly, or generate .o files from assembler.
                    if (handledByLtoIndexing(a, allowLtoIndexing)) {
                        // The LTO artifacts that should be included in the final link
                        // are listed in the thinltoParamFile, generated by the LTO indexing.

                        // Even if this object file is being skipped for exposure as a Build variable, it's
                        // still an input to this action.
                        expandedLinkerInputsBuilder.add(LinkerInputs.simpleLinkerInput(a,
                                ArtifactCategory.OBJECT_FILE, /* disableWholeArchive= */ false));
                        continue;
                    }
                    // No LTO indexing step, so use the LTO backend's generated artifact directly
                    // instead of the bitcode object.
                    member = a;
                }
                nonLtoArchiveMembersBuilder.add(member);
                expandedLinkerInputsBuilder.add(LinkerInputs.simpleLinkerInput(member,
                        ArtifactCategory.OBJECT_FILE, /* disableWholeArchive  = */ false));
            }
            ImmutableList<Artifact> nonLtoArchiveMembers = nonLtoArchiveMembersBuilder.build();
            if (!nonLtoArchiveMembers.isEmpty()) {
                if (inputIsWholeArchive) {
                    for (Artifact member : nonLtoArchiveMembers) {
                        if (member.isTreeArtifact()) {
                            // TODO(b/78189629): This object filegroup is expanded at action time but wrapped
                            // with --start/--end-lib. There's currently no way to force these objects to be
                            // linked in.
                            librariesToLink.addValue(LibraryToLinkValue.forObjectFileGroup(
                                    ImmutableList.<Artifact>of(member), /* isWholeArchive= */ true));
                        } else {
                            // TODO(b/78189629): These each need to be their own LibraryToLinkValue so they're
                            // not wrapped in --start/--end-lib (which lets the linker leave out objects with
                            // unreferenced code).
                            librariesToLink.addValue(LibraryToLinkValue.forObjectFile(
                                    effectiveObjectFilePath(member, input.isFake()),
                                    /* isWholeArchive= */ true));
                        }
                    }
                } else {
                    librariesToLink.addValue(LibraryToLinkValue.forObjectFileGroup(nonLtoArchiveMembers,
                            /* isWholeArchive= */ false));
                }
            }
        }
    } else {
        Artifact inputArtifact = input.getArtifact();
        Artifact a;
        if (ltoMap != null && (a = ltoMap.remove(inputArtifact)) != null) {
            if (handledByLtoIndexing(a, allowLtoIndexing)) {
                // The LTO artifacts that should be included in the final link
                // are listed in the thinltoParamFile, generated by the LTO indexing.

                // Even if this object file is being skipped for exposure as a build variable, it's
                // still an input to this action.
                expandedLinkerInputsBuilder.add(LinkerInputs.simpleLinkerInput(a, ArtifactCategory.OBJECT_FILE,
                        /* disableWholeArchive= */ false));
                return;
            }
            // No LTO indexing step, so use the LTO backend's generated artifact directly
            // instead of the bitcode object.
            inputArtifact = a;
        }

        if (artifactCategory.equals(ArtifactCategory.OBJECT_FILE)) {
            if (inputArtifact.isTreeArtifact()) {
                librariesToLink.addValue(LibraryToLinkValue
                        .forObjectFileGroup(ImmutableList.<Artifact>of(inputArtifact), inputIsWholeArchive));
            } else {
                librariesToLink.addValue(LibraryToLinkValue.forObjectFile(
                        effectiveObjectFilePath(inputArtifact, input.isFake()), inputIsWholeArchive));
            }
            expandedLinkerInputsBuilder.add(input);
        } else {
            librariesToLink.addValue(LibraryToLinkValue.forStaticLibrary(
                    effectiveObjectFilePath(inputArtifact, input.isFake()), inputIsWholeArchive));
            expandedLinkerInputsBuilder.add(input);
        }
    }
}