Example usage for com.google.common.collect Streams stream

List of usage examples for com.google.common.collect Streams stream

Introduction

In this page you can find the example usage for com.google.common.collect Streams stream.

Prototype

public static DoubleStream stream(OptionalDouble optional) 

Source Link

Document

If a value is present in optional , returns a stream containing only that element, otherwise returns an empty stream.

Usage

From source file:com.facebook.buck.tools.documentation.generator.skylark.rendering.SoyTemplateSkylarkSignatureRenderer.java

/** Renders a table of contents for the Skylark functions subsection on buckbuild.com website. */
public String renderTableOfContents(Iterable<SkylarkCallable> signatures) {
    ST stringTemplate = createTemplate(TABLE_OF_CONTENTS_TEMPLATE_NAME);
    stringTemplate.add("openCurly", "{");
    stringTemplate.add("closeCurly", "}");
    stringTemplate.add("signatures",
            Streams.stream(signatures).sorted(Comparator.comparing(SkylarkCallable::name))
                    .map(SoyTemplateSkylarkSignatureRenderer::toMap).collect(Collectors.toList()));
    return stringTemplate.render();
}

From source file:org.graylog2.lookup.db.DBDataAdapterService.java

public Stream<DataAdapterDto> streamAll() {
    return Streams.stream((Iterable<DataAdapterDto>) db.find());
}

From source file:org.onosproject.artemis.impl.ArtemisConfig.java

/**
 * Gets the set of monitored prefixes with the details (prefix, paths and MOAS).
 *
 * @return artemis class prefixes/*from  w  ww. j a  v  a  2s.  c o m*/
 */
Set<ArtemisPrefixes> monitoredPrefixes() {
    Set<ArtemisPrefixes> prefixes = Sets.newHashSet();

    JsonNode prefixesNode = object.path(PREFIXES);
    if (prefixesNode.isMissingNode()) {
        log.warn("prefixes field is null!");
        return prefixes;
    }

    prefixesNode.forEach(jsonNode -> {
        IpPrefix prefix = IpPrefix.valueOf(jsonNode.get(PREFIX).asText());

        JsonNode moasNode = jsonNode.get(MOAS);
        Set<IpAddress> moasIps = Streams.stream(moasNode).map(asn -> IpAddress.valueOf(asn.asText()))
                .collect(Collectors.toSet());

        JsonNode pathsNode = jsonNode.get(PATHS);
        Map<Integer, Map<Integer, Set<Integer>>> paths = Maps.newHashMap();
        pathsNode.forEach(path -> addPath(paths, path));

        prefixes.add(new ArtemisPrefixes(prefix, moasIps, paths));
    });

    return prefixes;
}

From source file:com.linecorp.armeria.common.util.AbstractOptions.java

/**
 * Creates a new instance.//from   w ww  . ja va 2  s.  co m
 *
 * @param <T> the type of the {@link AbstractOptionValue}
 * @param valueFilter the {@link Function} to apply to the elements of the specified {@code values}
 * @param baseOptions the base options to merge
 * @param values the option values
 */
protected <T extends AbstractOptionValue<?, ?>> AbstractOptions(Function<T, T> valueFilter,
        AbstractOptions baseOptions, Iterable<T> values) {
    requireNonNull(baseOptions, "baseOptions");
    requireNonNull(valueFilter, "valueFilter");
    requireNonNull(values, "values");

    valueMap = new IdentityHashMap<>(baseOptions.valueMap);
    putAll(valueFilter, Streams.stream(values));
}

From source file:org.onosproject.openstacknetworkingui.OpenstackNetworkingUiManager.java

@Activate
protected void activate() {
    uiExtensionService.register(extension);

    vDevices = Streams.stream(deviceService.getAvailableDevices()).filter(this::isVirtualDevice)
            .collect(Collectors.toSet());

    vDevices.forEach(this::createLinksConnectedToTargetvDevice);

    log.info("Started");
}

From source file:com.google.cloud.runtimes.tomcat.session.DatastoreStore.java

/**
 * Return the number of Sessions present in this Store.
 *
 * <p>The Datastore does not support counting elements in a collection.
 * So, all keys are fetched and the counted locally.</p>
 *
 * <p>This method may be slow if a large number of sessions are persisted,
 * prefer operations on individual entities rather than aggregations.</p>
 *
 * @return The number of sessions stored into the Datastore
 *///from   w ww  .  j  a v  a2s .c  o  m
@Override
public int getSize() throws IOException {
    log.debug("Accessing sessions count, be cautious this operation can cause performance issues");
    Query<Key> query = Query.newKeyQueryBuilder().build();
    QueryResults<Key> results = datastore.run(query);
    long count = Streams.stream(results).count();
    return Math.toIntExact(count);
}

From source file:de.learnlib.oracle.equivalence.AbstractTestWordEQOracle.java

private Stream<DefaultQuery<I, D>> answerQueries(final Stream<DefaultQuery<I, D>> stream) {
    if (isBatched()) {
        /*/*from w  w  w . j  av  a 2 s  .  co m*/
         * FIXME: currently necessary because of a bug in the JDK
         * see https://bugs.openjdk.java.net/browse/JDK-8075939
         */
        return Streams.stream(Streams.stream(new BatchingIterator<>(stream.iterator(), this.batchSize))
                .peek(membershipOracle::processQueries).flatMap(List::stream).iterator());
    } else {
        return stream.peek(membershipOracle::processQuery);
    }
}

From source file:com.google.devtools.build.lib.query2.ActionGraphTextOutputFormatterCallback.java

private void writeAction(ActionAnalysisMetadata action, PrintStream printStream)
        throws IOException, CommandLineExpansionException {
    ActionOwner actionOwner = action.getOwner();
    StringBuilder stringBuilder = new StringBuilder();
    stringBuilder.append(action.prettyPrint()).append('\n').append("  Mnemonic: ").append(action.getMnemonic())
            .append('\n');

    if (actionOwner != null) {
        BuildEvent configuration = actionOwner.getConfiguration();
        BuildEventStreamProtos.Configuration configProto = configuration.asStreamProto(/*context=*/ null)
                .getConfiguration();/*from ww  w  .  j  a  va 2s  .  co  m*/
        stringBuilder.append("  Owner: ").append(actionOwner.getLabel().toString()).append('\n')
                .append("  Configuration: ").append(configProto.getMnemonic()).append('\n');
    }

    if (action instanceof ActionExecutionMetadata) {
        ActionExecutionMetadata actionExecutionMetadata = (ActionExecutionMetadata) action;
        stringBuilder.append("  ActionKey: ").append(actionExecutionMetadata.getKey(actionKeyContext))
                .append('\n');
    }

    stringBuilder.append("  Inputs: [")
            .append(Streams.stream(action.getInputs()).map(input -> input.getExecPathString()).sorted()
                    .collect(Collectors.joining(", ")))
            .append("]\n").append("  Outputs: [").append(Streams.stream(action.getOutputs())
                    .map(input -> input.getExecPathString()).sorted().collect(Collectors.joining(", ")))
            .append("]\n");

    if (action instanceof SpawnAction) {
        SpawnAction spawnAction = (SpawnAction) action;
        // TODO(twerth): This handles the fixed environment. We probably want to output the inherited
        // environment as well.
        ImmutableMap<String, String> fixedEnvironment = spawnAction.getEnvironment().getFixedEnv();
        stringBuilder.append("  Environment: [").append(Streams.stream(fixedEnvironment.entrySet())
                .map(environmentVariable -> environmentVariable.getKey() + "=" + environmentVariable.getValue())
                .sorted().collect(Collectors.joining(", "))).append("]\n")

                // TODO(twerth): Add option to only optionally include the command line.
                .append("  Command Line: ")
                .append(CommandFailureUtils.describeCommand(CommandDescriptionForm.COMPLETE,
                        /* prettyPrintArgs= */ true, spawnAction.getArguments(), /* environment= */ null,
                        /* cwd= */ null))
                .append("\n");
    }

    stringBuilder.append('\n');

    printStream.write(stringBuilder.toString().getBytes(UTF_8));
}

From source file:com.facebook.buck.io.file.MorePaths.java

/**
 * Filters out {@link Path} objects from {@code paths} that aren't a subpath of {@code root} and
 * returns a set of paths relative to {@code root}.
 *//*  ww w . ja  v  a2 s .  com*/
public static ImmutableSet<Path> filterForSubpaths(Iterable<Path> paths, Path root) {
    Path normalizedRoot = root.toAbsolutePath().normalize();
    return Streams.stream(paths).filter(input -> {
        if (input.isAbsolute()) {
            return input.normalize().startsWith(normalizedRoot);
        } else {
            return true;
        }
    }).map(input -> {
        if (input.isAbsolute()) {
            return relativize(normalizedRoot, input);
        } else {
            return input;
        }
    }).collect(ImmutableSet.toImmutableSet());
}

From source file:com.facebook.presto.operator.aggregation.PrecisionRecallAggregation.java

protected static Iterator<BucketResult> getResultsIterator(@AggregationState PrecisionRecallState state) {
    if (state.getTrueWeights() == null) {
        return Collections.<BucketResult>emptyList().iterator();
    }/* w w w. j a  v a  2  s  .  com*/

    final double totalTrueWeight = Streams.stream(state.getTrueWeights().iterator()).mapToDouble(c -> c.weight)
            .sum();
    final double totalFalseWeight = Streams.stream(state.getFalseWeights().iterator())
            .mapToDouble(c -> c.weight).sum();

    return new Iterator<BucketResult>() {
        Iterator<FixedDoubleHistogram.Bin> trueIt = state.getTrueWeights().iterator();
        Iterator<FixedDoubleHistogram.Bin> falseIt = state.getFalseWeights().iterator();
        double runningFalseWeight;
        double runningTrueWeight;

        @Override
        public boolean hasNext() {
            return trueIt.hasNext() && totalTrueWeight > runningTrueWeight;
        }

        @Override
        public BucketResult next() {
            if (!trueIt.hasNext() || !falseIt.hasNext()) {
                throw new NoSuchElementException();
            }
            final FixedDoubleHistogram.Bin trueResult = trueIt.next();
            final FixedDoubleHistogram.Bin falseResult = falseIt.next();

            final BucketResult result = new BucketResult(trueResult.left, trueResult.right, totalTrueWeight,
                    totalFalseWeight, runningTrueWeight, runningFalseWeight);

            runningTrueWeight += trueResult.weight;
            runningFalseWeight += falseResult.weight;

            return result;
        }

        @Override
        public void remove() {
            throw new UnsupportedOperationException();
        }
    };
}