Example usage for com.google.common.base Functions constant

List of usage examples for com.google.common.base Functions constant

Introduction

In this page you can find the example usage for com.google.common.base Functions constant.

Prototype

public static <E> Function<Object, E> constant(@Nullable E value) 

Source Link

Document

Creates a function that returns value for any input.

Usage

From source file:de.bund.bfr.knime.nls.chart.ChartConfigPanel.java

public void setParamValues(Map<String, Double> values, Map<String, Double> minValues,
        Map<String, Double> maxValues) {
    if (outerParameterPanel != null) {
        outerParameterPanel.removeAll();
        parameterPanel = new VariablePanel(
                Maps.asMap(parameterPanel.getValues().keySet(), Functions.constant(new ArrayList<>())),
                minValues, maxValues, false, true, true);
        parameterPanel.setValues(values);
        parameterPanel.addValueListener(e -> fireConfigChanged());
        outerParameterPanel.add(parameterPanel, BorderLayout.WEST);

        Container container = getParent();

        while (container != null) {
            if (container instanceof JPanel) {
                ((JPanel) container).revalidate();
                break;
            }//  w  w  w.  jav a  2  s  . c  o m

            container = container.getParent();
        }
    }
}

From source file:de.bund.bfr.knime.nls.chart.ChartConfigPanel.java

public void setVariableValues(Map<String, Double> values, Map<String, Double> minValues,
        Map<String, Double> maxValues) {
    if (outerVariablePanel != null) {
        outerVariablePanel.removeAll();/*  www  .j  a v  a  2 s. c o  m*/
        variablePanel = new VariablePanel(
                Maps.asMap(variablePanel.getValues().keySet(), Functions.constant(new ArrayList<>())),
                minValues, maxValues, false, true, true);
        variablePanel.setValues(values);
        variablePanel.setEnabled(getVarX(), false);
        variablePanel.addValueListener(e -> fireConfigChanged());
        outerVariablePanel.add(variablePanel, BorderLayout.WEST);

        Container container = getParent();

        while (container != null) {
            if (container instanceof JPanel) {
                ((JPanel) container).revalidate();
                break;
            }

            container = container.getParent();
        }
    }
}

From source file:brooklyn.entity.nosql.cassandra.CassandraNodeImpl.java

@SuppressWarnings({ "unchecked", "rawtypes" })
@Override//w  w w .java  2s  .  c  om
protected void connectSensors() {
    // "cassandra" isn't really a protocol, but okay for now
    setAttribute(DATASTORE_URL, "cassandra://" + getAttribute(HOSTNAME) + ":" + getAttribute(THRIFT_PORT));

    super.connectSensors();

    jmxHelper = new JmxHelper(this);
    jmxFeed = JmxFeed.builder().entity(this).period(3000, TimeUnit.MILLISECONDS).helper(jmxHelper)
            .pollAttribute(new JmxAttributePollConfig<Boolean>(SERVICE_UP_JMX).objectName(storageServiceMBean)
                    .attributeName("Initialized").onSuccess(Functions.forPredicate(Predicates.notNull()))
                    .onException(Functions.constant(false)))
            .pollAttribute(new JmxAttributePollConfig<Set<BigInteger>>(TOKENS).objectName(storageServiceMBean)
                    .attributeName("TokenToEndpointMap").onSuccess(new Function<Object, Set<BigInteger>>() {
                        @Override
                        public Set<BigInteger> apply(@Nullable Object arg) {
                            Map input = (Map) arg;
                            if (input == null || input.isEmpty())
                                return null;
                            // FIXME does not work on aws-ec2, uses RFC1918 address
                            Predicate<String> self = Predicates
                                    .in(ImmutableList.of(getAttribute(HOSTNAME), getAttribute(ADDRESS),
                                            getAttribute(SUBNET_ADDRESS), getAttribute(SUBNET_HOSTNAME)));
                            Set<String> tokens = Maps.filterValues(input, self).keySet();
                            Set<BigInteger> result = Sets.newLinkedHashSet();
                            for (String token : tokens) {
                                result.add(new BigInteger(token));
                            }
                            return result;
                        }
                    }).onException(Functions.<Set<BigInteger>>constant(null)))
            .pollAttribute(new JmxAttributePollConfig<BigInteger>(TOKEN).objectName(storageServiceMBean)
                    .attributeName("TokenToEndpointMap").onSuccess(new Function<Object, BigInteger>() {
                        @Override
                        public BigInteger apply(@Nullable Object arg) {
                            Map input = (Map) arg;
                            // TODO remove duplication from setting TOKENS
                            if (input == null || input.isEmpty())
                                return null;
                            // FIXME does not work on aws-ec2, uses RFC1918 address
                            Predicate<String> self = Predicates
                                    .in(ImmutableList.of(getAttribute(HOSTNAME), getAttribute(ADDRESS),
                                            getAttribute(SUBNET_ADDRESS), getAttribute(SUBNET_HOSTNAME)));
                            Set<String> tokens = Maps.filterValues(input, self).keySet();
                            String token = Iterables.getFirst(tokens, null);
                            return (token != null) ? new BigInteger(token) : null;
                        }
                    }).onException(Functions.<BigInteger>constant(null)))
            .pollOperation(new JmxOperationPollConfig<String>(DATACENTER_NAME).period(60, TimeUnit.SECONDS)
                    .objectName(snitchMBean).operationName("getDatacenter")
                    .operationParams(ImmutableList.of(getBroadcastAddress()))
                    .onException(Functions.<String>constant(null)))
            .pollOperation(new JmxOperationPollConfig<String>(RACK_NAME).period(60, TimeUnit.SECONDS)
                    .objectName(snitchMBean).operationName("getRack")
                    .operationParams(ImmutableList.of(getBroadcastAddress()))
                    .onException(Functions.<String>constant(null)))
            .pollAttribute(new JmxAttributePollConfig<Integer>(PEERS).objectName(storageServiceMBean)
                    .attributeName("TokenToEndpointMap").onSuccess(new Function<Object, Integer>() {
                        @Override
                        public Integer apply(@Nullable Object arg) {
                            Map input = (Map) arg;
                            if (input == null || input.isEmpty())
                                return 0;
                            return input.size();
                        }
                    }).onException(Functions.constant(-1)))
            .pollAttribute(new JmxAttributePollConfig<Integer>(LIVE_NODE_COUNT).objectName(storageServiceMBean)
                    .attributeName("LiveNodes").onSuccess(new Function<Object, Integer>() {
                        @Override
                        public Integer apply(@Nullable Object arg) {
                            List input = (List) arg;
                            if (input == null || input.isEmpty())
                                return 0;
                            return input.size();
                        }
                    }).onException(Functions.constant(-1)))
            .pollAttribute(new JmxAttributePollConfig<Integer>(READ_ACTIVE).objectName(readStageMBean)
                    .attributeName("ActiveCount").onException(Functions.constant((Integer) null)))
            .pollAttribute(new JmxAttributePollConfig<Long>(READ_PENDING).objectName(readStageMBean)
                    .attributeName("PendingTasks").onException(Functions.constant((Long) null)))
            .pollAttribute(new JmxAttributePollConfig<Long>(READ_COMPLETED).objectName(readStageMBean)
                    .attributeName("CompletedTasks").onException(Functions.constant((Long) null)))
            .pollAttribute(new JmxAttributePollConfig<Integer>(WRITE_ACTIVE).objectName(mutationStageMBean)
                    .attributeName("ActiveCount").onException(Functions.constant((Integer) null)))
            .pollAttribute(new JmxAttributePollConfig<Long>(WRITE_PENDING).objectName(mutationStageMBean)
                    .attributeName("PendingTasks").onException(Functions.constant((Long) null)))
            .pollAttribute(new JmxAttributePollConfig<Long>(WRITE_COMPLETED).objectName(mutationStageMBean)
                    .attributeName("CompletedTasks").onException(Functions.constant((Long) null)))
            .build();

    functionFeed = FunctionFeed.builder().entity(this).period(3000, TimeUnit.MILLISECONDS)
            .poll(new FunctionPollConfig<Long, Long>(THRIFT_PORT_LATENCY)
                    .onException(Functions.constant((Long) null)).callable(new Callable<Long>() {
                        public Long call() {
                            try {
                                long start = System.currentTimeMillis();
                                Socket s = new Socket(getAttribute(Attributes.HOSTNAME), getThriftPort());
                                s.close();
                                long latency = System.currentTimeMillis() - start;
                                computeServiceUp();
                                return latency;
                            } catch (Exception e) {
                                if (log.isDebugEnabled())
                                    log.debug("Cassandra thrift port poll failure: " + e);
                                setAttribute(SERVICE_UP, false);
                                return null;
                            }
                        }

                        public void computeServiceUp() {
                            // this will wait an additional poll period after thrift port is up,
                            // as the caller will not have set yet, but that will help ensure it is really healthy!
                            setAttribute(SERVICE_UP,
                                    getAttribute(THRIFT_PORT_LATENCY) != null
                                            && getAttribute(THRIFT_PORT_LATENCY) >= 0
                                            && Boolean.TRUE.equals(getAttribute(SERVICE_UP_JMX)));
                        }
                    }))
            .build();

    jmxMxBeanFeed = JavaAppUtils.connectMXBeanSensors(this);
}

From source file:org.apache.brooklyn.entity.nosql.cassandra.CassandraNodeImpl.java

@SuppressWarnings({ "unchecked", "rawtypes" })
@Override//w  ww.j  a v  a 2 s .  co m
protected void connectSensors() {
    // "cassandra" isn't really a protocol, but okay for now
    sensors().set(DATASTORE_URL, "cassandra://" + getAttribute(HOSTNAME) + ":" + getAttribute(THRIFT_PORT));

    super.connectSensors();

    jmxHelper = new JmxHelper(this);
    boolean retrieveUsageMetrics = getConfig(RETRIEVE_USAGE_METRICS);

    if (getDriver().isJmxEnabled()) {
        jmxFeed = JmxFeed.builder().entity(this).period(3000, TimeUnit.MILLISECONDS).helper(jmxHelper)
                .pollAttribute(new JmxAttributePollConfig<Boolean>(SERVICE_UP_JMX)
                        .objectName(storageServiceMBean).attributeName("Initialized")
                        .onSuccess(Functions.forPredicate(Predicates.notNull()))
                        .onException(Functions.constant(false)).suppressDuplicates(true))
                .pollAttribute(new JmxAttributePollConfig<Set<BigInteger>>(TOKENS)
                        .objectName(storageServiceMBean).attributeName("TokenToEndpointMap")
                        .onSuccess(new Function<Object, Set<BigInteger>>() {
                            @Override
                            public Set<BigInteger> apply(@Nullable Object arg) {
                                Map input = (Map) arg;
                                if (input == null || input.isEmpty())
                                    return null;
                                // FIXME does not work on aws-ec2, uses RFC1918 address
                                Predicate<String> self = Predicates
                                        .in(ImmutableList.of(getAttribute(HOSTNAME), getAttribute(ADDRESS),
                                                getAttribute(SUBNET_ADDRESS), getAttribute(SUBNET_HOSTNAME)));
                                Set<String> tokens = Maps.filterValues(input, self).keySet();
                                Set<BigInteger> result = Sets.newLinkedHashSet();
                                for (String token : tokens) {
                                    result.add(new BigInteger(token));
                                }
                                return result;
                            }
                        }).onException(Functions.<Set<BigInteger>>constant(null)).suppressDuplicates(true))
                .pollOperation(new JmxOperationPollConfig<String>(DATACENTER_NAME).period(60, TimeUnit.SECONDS)
                        .objectName(snitchMBean).operationName("getDatacenter")
                        .operationParams(ImmutableList.of(getBroadcastAddress()))
                        .onException(Functions.<String>constant(null)).suppressDuplicates(true))
                .pollOperation(new JmxOperationPollConfig<String>(RACK_NAME).period(60, TimeUnit.SECONDS)
                        .objectName(snitchMBean).operationName("getRack")
                        .operationParams(ImmutableList.of(getBroadcastAddress()))
                        .onException(Functions.<String>constant(null)).suppressDuplicates(true))
                .pollAttribute(new JmxAttributePollConfig<Integer>(PEERS).objectName(storageServiceMBean)
                        .attributeName("TokenToEndpointMap").onSuccess(new Function<Object, Integer>() {
                            @Override
                            public Integer apply(@Nullable Object arg) {
                                Map input = (Map) arg;
                                if (input == null || input.isEmpty())
                                    return 0;
                                return input.size();
                            }
                        }).onException(Functions.constant(-1)))
                .pollAttribute(
                        new JmxAttributePollConfig<Integer>(LIVE_NODE_COUNT).objectName(storageServiceMBean)
                                .attributeName("LiveNodes").onSuccess(new Function<Object, Integer>() {
                                    @Override
                                    public Integer apply(@Nullable Object arg) {
                                        List input = (List) arg;
                                        if (input == null || input.isEmpty())
                                            return 0;
                                        return input.size();
                                    }
                                }).onException(Functions.constant(-1)))
                .pollAttribute(new JmxAttributePollConfig<Integer>(READ_ACTIVE).objectName(readStageMBean)
                        .attributeName("ActiveCount").onException(Functions.constant((Integer) null))
                        .enabled(retrieveUsageMetrics))
                .pollAttribute(new JmxAttributePollConfig<Long>(READ_PENDING).objectName(readStageMBean)
                        .attributeName("PendingTasks").onException(Functions.constant((Long) null))
                        .enabled(retrieveUsageMetrics))
                .pollAttribute(new JmxAttributePollConfig<Long>(READ_COMPLETED).objectName(readStageMBean)
                        .attributeName("CompletedTasks").onException(Functions.constant((Long) null))
                        .enabled(retrieveUsageMetrics))
                .pollAttribute(new JmxAttributePollConfig<Integer>(WRITE_ACTIVE).objectName(mutationStageMBean)
                        .attributeName("ActiveCount").onException(Functions.constant((Integer) null))
                        .enabled(retrieveUsageMetrics))
                .pollAttribute(new JmxAttributePollConfig<Long>(WRITE_PENDING).objectName(mutationStageMBean)
                        .attributeName("PendingTasks").onException(Functions.constant((Long) null))
                        .enabled(retrieveUsageMetrics))
                .pollAttribute(new JmxAttributePollConfig<Long>(WRITE_COMPLETED).objectName(mutationStageMBean)
                        .attributeName("CompletedTasks").onException(Functions.constant((Long) null))
                        .enabled(retrieveUsageMetrics))
                .build();

        jmxMxBeanFeed = JavaAppUtils.connectMXBeanSensors(this);
    }

    if (Boolean.TRUE.equals(getConfig(USE_THRIFT_MONITORING))) {
        functionFeed = FunctionFeed.builder().entity(this).period(3000, TimeUnit.MILLISECONDS)
                .poll(new FunctionPollConfig<Long, Long>(THRIFT_PORT_LATENCY)
                        .onException(Functions.constant(-1L))
                        .callable(new ThriftLatencyChecker(CassandraNodeImpl.this))
                        .enabled(retrieveUsageMetrics))
                .build();
    }

    connectServiceUpIsRunning();
}

From source file:com.netflix.metacat.connector.hive.sql.DirectSqlGetPartition.java

private List<PartitionHolder> getPartitions(final String databaseName, final String tableName,
        @Nullable final List<String> partitionIds, @Nullable final String filterExpression,
        @Nullable final Sort sort, @Nullable final Pageable pageable, final boolean includePartitionDetails,
        final boolean forceDisableAudit) {
    final FilterPartition filter = new FilterPartition();
    // batch exists
    final boolean isBatched = !Strings.isNullOrEmpty(filterExpression)
            && filterExpression.contains(FIELD_BATCHID);
    final boolean hasDateCreated = !Strings.isNullOrEmpty(filterExpression)
            && filterExpression.contains(FIELD_DATE_CREATED);
    // Handler for reading the result set
    final ResultSetExtractor<List<PartitionHolder>> handler = rs -> {
        final List<PartitionHolder> result = Lists.newArrayList();
        while (rs.next()) {
            final String name = rs.getString("name");
            final String uri = rs.getString("uri");
            final long createdDate = rs.getLong(FIELD_DATE_CREATED);
            Map<String, String> values = null;
            if (hasDateCreated) {
                values = Maps.newHashMap();
                values.put(FIELD_DATE_CREATED, createdDate + "");
            }//from ww w  .  jav  a  2 s .  c o m
            if (Strings.isNullOrEmpty(filterExpression)
                    || filter.evaluatePartitionExpression(filterExpression, name, uri, isBatched, values)) {
                final Long id = rs.getLong("id");
                final Long sdId = rs.getLong("sd_id");
                final Long serdeId = rs.getLong("serde_id");
                final String inputFormat = rs.getString("input_format");
                final String outputFormat = rs.getString("output_format");
                final String serializationLib = rs.getString("slib");
                final StorageInfo storageInfo = new StorageInfo();
                storageInfo.setUri(uri);
                storageInfo.setInputFormat(inputFormat);
                storageInfo.setOutputFormat(outputFormat);
                storageInfo.setSerializationLib(serializationLib);
                final AuditInfo auditInfo = new AuditInfo();
                auditInfo.setCreatedDate(Date.from(Instant.ofEpochSecond(createdDate)));
                auditInfo.setLastModifiedDate(Date.from(Instant.ofEpochSecond(createdDate)));

                result.add(new PartitionHolder(id, sdId, serdeId,
                        PartitionInfo.builder()
                                .name(QualifiedName.ofPartition(catalogName, databaseName, tableName, name))
                                .auditInfo(auditInfo).serde(storageInfo).build()));
            }
        }
        return result;
    };

    final List<PartitionHolder> partitions = this.getHandlerResults(databaseName, tableName, filterExpression,
            partitionIds, SQL.SQL_GET_PARTITIONS, handler, sort, pageable, forceDisableAudit);

    if (includePartitionDetails && !partitions.isEmpty()) {
        final List<Long> partIds = Lists.newArrayListWithCapacity(partitions.size());
        final List<Long> sdIds = Lists.newArrayListWithCapacity(partitions.size());
        final List<Long> serdeIds = Lists.newArrayListWithCapacity(partitions.size());
        for (PartitionHolder partitionHolder : partitions) {
            partIds.add(partitionHolder.getId());
            sdIds.add(partitionHolder.getSdId());
            serdeIds.add(partitionHolder.getSerdeId());
        }
        final List<ListenableFuture<Void>> futures = Lists.newArrayList();
        final Map<Long, Map<String, String>> partitionParams = Maps.newHashMap();
        futures.add(threadServiceManager.getExecutor().submit(
                () -> populateParameters(partIds, SQL.SQL_GET_PARTITION_PARAMS, "part_id", partitionParams)));

        final Map<Long, Map<String, String>> sdParams = Maps.newHashMap();
        if (!sdIds.isEmpty()) {
            futures.add(threadServiceManager.getExecutor()
                    .submit(() -> populateParameters(sdIds, SQL.SQL_GET_SD_PARAMS, "sd_id", sdParams)));
        }
        final Map<Long, Map<String, String>> serdeParams = Maps.newHashMap();
        if (!serdeIds.isEmpty()) {
            futures.add(threadServiceManager.getExecutor().submit(
                    () -> populateParameters(serdeIds, SQL.SQL_GET_SERDE_PARAMS, "serde_id", serdeParams)));
        }
        try {
            Futures.transform(Futures.successfulAsList(futures), Functions.constant(null)).get(1,
                    TimeUnit.HOURS);
        } catch (Exception e) {
            Throwables.propagate(e);
        }

        for (PartitionHolder partitionHolder : partitions) {
            partitionHolder.getPartitionInfo().setMetadata(partitionParams.get(partitionHolder.getId()));
            partitionHolder.getPartitionInfo().getSerde()
                    .setParameters(sdParams.get(partitionHolder.getSdId()));
            partitionHolder.getPartitionInfo().getSerde()
                    .setSerdeInfoParameters(serdeParams.get(partitionHolder.getSerdeId()));

        }
    }
    return partitions;
}

From source file:com.google.devtools.common.options.OptionsParser.java

/**
 * Parses {@code args}, using the classes registered with this parser.
 * {@link #getOptions(Class)} and {@link #getResidue()} return the results.
 * May be called multiple times; later options override existing ones if they
 * have equal or higher priority. The source of options is a free-form string
 * that can be used for debugging. Strings that cannot be parsed as options
 * accumulates as residue, if this parser allows it.
 *
 * @see OptionPriority//from www  .j a v a  2 s . c  o  m
 */
public void parse(OptionPriority priority, String source, List<String> args) throws OptionsParsingException {
    parseWithSourceFunction(priority, Functions.constant(source), args);
}

From source file:com.android.build.gradle.tasks.PackageAndroidArtifact.java

/**
 * Obtains all changed inputs of a given input set. Given a set of files mapped to their
 * changed status, this method returns a list of changes computed as follows:
 *
 * <ol>//from  ww  w  .j  a  v  a  2s .  c o m
 *     <li>Changed inputs are split into deleted and non-deleted inputs. This separation is
 *     needed because deleted inputs may no longer be mappable to any {@link InputSet} just
 *     by looking at the file path, without using {@link KnownFilesSaveData}.
 *     <li>Deleted inputs are filtered through {@link KnownFilesSaveData} to get only those
 *     whose input set matches {@code inputSet}.
 *     <li>Non-deleted inputs are processed through
 *     {@link IncrementalRelativeFileSets#makeFromBaseFiles(Collection, Map, FileCacheByPath)}
 *     to obtain the incremental file changes.
 *     <li>The results of processed deleted and non-deleted are merged and returned.
 * </ol>
 *
 * @param changedInputs all changed inputs
 * @param saveData the save data with all input sets from last run
 * @param inputSet the input set to filter
 * @param baseFiles the base files of the input set
 * @param cacheByPath where to cache files
 * @return the status of all relative files in the input set
 */
@NonNull
private ImmutableMap<RelativeFile, FileStatus> getChangedInputs(@NonNull Map<File, FileStatus> changedInputs,
        @NonNull KnownFilesSaveData saveData, @NonNull InputSet inputSet, @NonNull Collection<File> baseFiles,
        @NonNull FileCacheByPath cacheByPath) throws IOException {

    /*
     * Figure out changes to deleted files.
     */
    Set<File> deletedFiles = Maps.filterValues(changedInputs, Predicates.equalTo(FileStatus.REMOVED)).keySet();
    Set<RelativeFile> deletedRelativeFiles = saveData.find(deletedFiles, inputSet);

    /*
     * Figure out changes to non-deleted files.
     */
    Map<File, FileStatus> nonDeletedFiles = Maps.filterValues(changedInputs,
            Predicates.not(Predicates.equalTo(FileStatus.REMOVED)));
    Map<RelativeFile, FileStatus> nonDeletedRelativeFiles = IncrementalRelativeFileSets
            .makeFromBaseFiles(baseFiles, nonDeletedFiles, cacheByPath);

    /*
     * Merge everything.
     */
    return new ImmutableMap.Builder<RelativeFile, FileStatus>()
            .putAll(Maps.asMap(deletedRelativeFiles, Functions.constant(FileStatus.REMOVED)))
            .putAll(nonDeletedRelativeFiles).build();
}

From source file:com.netflix.metacat.main.services.search.ElasticSearchMetacatRefresh.java

@SuppressWarnings("checkstyle:methodname")
private ListenableFuture<Void> _processCatalogs(final List<String> catalogNames) {
    log.info("Start: Full refresh of catalogs: {}", catalogNames);
    final List<ListenableFuture<CatalogDto>> getCatalogFutures = catalogNames.stream()
            .map(catalogName -> service.submit(() -> {
                CatalogDto result = null;
                try {
                    result = getCatalog(catalogName);
                } catch (Exception e) {
                    log.error("Failed to retrieve catalog: {}", catalogName);
                    elasticSearchUtil.log("ElasticSearchMetacatRefresh.getCatalog",
                            ElasticSearchDoc.Type.catalog.name(), catalogName, null, e.getMessage(), e, true);
                }/*from   w w  w  . ja v  a 2  s  .  co m*/
                return result;
            })).collect(Collectors.toList());
    return Futures.transformAsync(Futures.successfulAsList(getCatalogFutures), input -> {
        final List<ListenableFuture<Void>> processCatalogFutures = input.stream().filter(NOT_NULL)
                .map(catalogDto -> {
                    final List<QualifiedName> databaseNames = getDatabaseNamesToRefresh(catalogDto);
                    return _processDatabases(catalogDto.getName(), databaseNames);
                }).filter(NOT_NULL).collect(Collectors.toList());
        return Futures.transform(Futures.successfulAsList(processCatalogFutures), Functions.constant(null));
    });
}

From source file:com.google.devtools.common.options.OptionsParserImpl.java

/**
 * Parses the args, and returns what it doesn't parse. May be called multiple
 * times, and may be called recursively. Calls may contain intersecting sets
 * of options; in that case, the arg seen last takes precedence.
 *
 * <p>The method uses the invariant that if an option has neither an implicit
 * dependent nor an expanded from value, then it must have been explicitly
 * set./*  ww w.ja v a 2s .c om*/
 */
private List<String> parse(OptionPriority priority, Function<? super String, String> sourceFunction,
        String implicitDependent, String expandedFrom, List<String> args) throws OptionsParsingException {

    List<String> unparsedArgs = Lists.newArrayList();
    LinkedHashMap<String, List<String>> implicitRequirements = Maps.newLinkedHashMap();

    Iterator<String> argsIterator = args.iterator();
    while (argsIterator.hasNext()) {
        String arg = argsIterator.next();

        if (!arg.startsWith("-")) {
            unparsedArgs.add(arg);
            continue; // not an option arg
        }

        if (arg.equals("--")) { // "--" means all remaining args aren't options
            Iterators.addAll(unparsedArgs, argsIterator);
            break;
        }

        ParseOptionResult optionParseResult = parseOption(arg, argsIterator);
        Field field = optionParseResult.field;
        Option option = optionParseResult.option;
        String value = optionParseResult.value;

        final String originalName = option.name();

        if (option.wrapperOption()) {
            if (value.startsWith("-")) {

                List<String> unparsed = parse(priority,
                        Functions.constant("Unwrapped from wrapper option --" + originalName), null, // implicitDependent
                        null, // expandedFrom
                        ImmutableList.of(value));

                if (!unparsed.isEmpty()) {
                    throw new OptionsParsingException("Unparsed options remain after unwrapping " + arg + ": "
                            + Joiner.on(' ').join(unparsed));
                }

                // Don't process implicitRequirements or expansions for wrapper options. In particular,
                // don't record this option in unparsedValues, so that only the wrapped option shows
                // up in canonicalized options.
                continue;

            } else {
                throw new OptionsParsingException("Invalid --" + originalName + " value format. "
                        + "You may have meant --" + originalName + "=--" + value);
            }
        }

        if (implicitDependent == null) {
            // Log explicit options and expanded options in the order they are parsed (can be sorted
            // later). Also remember whether they were expanded or not. This information is needed to
            // correctly canonicalize flags.
            UnparsedOptionValueDescription unparsedOptionValueDescription = new UnparsedOptionValueDescription(
                    originalName, field, value, priority, sourceFunction.apply(originalName),
                    expandedFrom == null);
            unparsedValues.add(unparsedOptionValueDescription);
            if (option.allowMultiple()) {
                canonicalizeValues.put(field, unparsedOptionValueDescription);
            } else {
                canonicalizeValues.replaceValues(field, ImmutableList.of(unparsedOptionValueDescription));
            }
        }

        // Handle expansion options.
        if (option.expansion().length > 0) {
            Function<Object, String> expansionSourceFunction = Functions.<String>constant(
                    "expanded from option --" + originalName + " from " + sourceFunction.apply(originalName));
            maybeAddDeprecationWarning(field);
            List<String> unparsed = parse(priority, expansionSourceFunction, null, originalName,
                    ImmutableList.copyOf(option.expansion()));
            if (!unparsed.isEmpty()) {
                // Throw an assertion, because this indicates an error in the code that specified the
                // expansion for the current option.
                throw new AssertionError("Unparsed options remain after parsing expansion of " + arg + ": "
                        + Joiner.on(' ').join(unparsed));
            }
        } else {
            Converter<?> converter = optionsData.getConverter(field);
            Object convertedValue;
            try {
                convertedValue = converter.convert(value);
            } catch (OptionsParsingException e) {
                // The converter doesn't know the option name, so we supply it here by
                // re-throwing:
                throw new OptionsParsingException("While parsing option " + arg + ": " + e.getMessage(), e);
            }

            // ...but allow duplicates of single-use options across separate calls to
            // parse(); latest wins:
            if (!option.allowMultiple()) {
                setValue(field, originalName, convertedValue, priority, sourceFunction.apply(originalName),
                        implicitDependent, expandedFrom);
            } else {
                // But if it's a multiple-use option, then just accumulate the
                // values, in the order in which they were seen.
                // Note: The type of the list member is not known; Java introspection
                // only makes it available in String form via the signature string
                // for the field declaration.
                addListValue(field, convertedValue, priority, sourceFunction.apply(originalName),
                        implicitDependent, expandedFrom);
            }
        }

        // Collect any implicit requirements.
        if (option.implicitRequirements().length > 0) {
            implicitRequirements.put(option.name(), Arrays.asList(option.implicitRequirements()));
        }
    }

    // Now parse any implicit requirements that were collected.
    // TODO(bazel-team): this should happen when the option is encountered.
    if (!implicitRequirements.isEmpty()) {
        for (Map.Entry<String, List<String>> entry : implicitRequirements.entrySet()) {
            Function<Object, String> requirementSourceFunction = Functions
                    .<String>constant("implicit requirement of option --" + entry.getKey() + " from "
                            + sourceFunction.apply(entry.getKey()));

            List<String> unparsed = parse(priority, requirementSourceFunction, entry.getKey(), null,
                    entry.getValue());
            if (!unparsed.isEmpty()) {
                // Throw an assertion, because this indicates an error in the code that specified in the
                // implicit requirements for the option(s).
                throw new AssertionError("Unparsed options remain after parsing implicit options: "
                        + Joiner.on(' ').join(unparsed));
            }
        }
    }

    return unparsedArgs;
}

From source file:com.netflix.metacat.main.services.search.ElasticSearchRefresh.java

@SuppressWarnings("checkstyle:methodname")
private ListenableFuture<Void> _processCatalogs(final List<String> catalogNames) {
    log.info("Start: Full refresh of catalogs: {}", catalogNames);
    final List<ListenableFuture<CatalogDto>> getCatalogFutures = catalogNames.stream()
            .map(catalogName -> service.submit(() -> {
                CatalogDto result = null;
                try {
                    result = getCatalog(catalogName);
                } catch (Exception e) {
                    log.error("Failed to retrieve catalog: {}", catalogName);
                    elasticSearchUtil.log("ElasticSearchRefresh.getCatalog",
                            ElasticSearchDoc.Type.catalog.name(), catalogName, null, e.getMessage(), e, true);
                }//from  w  ww.  ja va 2 s  .com
                return result;
            })).collect(Collectors.toList());
    return Futures.transformAsync(Futures.successfulAsList(getCatalogFutures), input -> {
        final List<ListenableFuture<Void>> processCatalogFutures = input.stream().filter(NOT_NULL)
                .map(catalogDto -> {
                    final List<QualifiedName> databaseNames = getDatabaseNamesToRefresh(catalogDto);
                    return _processDatabases(catalogDto.getName(), databaseNames);
                }).filter(NOT_NULL).collect(Collectors.toList());
        return Futures.transform(Futures.successfulAsList(processCatalogFutures), Functions.constant(null));
    });
}