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

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

Introduction

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

Prototype

default Stream<E> stream() 

Source Link

Document

Returns a sequential Stream with this collection as its source.

Usage

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;
    }//from  w w  w. ja v  a  2s .co  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.facebook.buck.skylark.parser.RuleFunctionFactory.java

/**
 * Validates attributes passed to the rule and in case any required attribute is not provided,
 * throws an {@link IllegalArgumentException}.
 *
 * @param kwargs The keyword arguments passed to the rule.
 * @param allParamInfo The mapping from build rule attributes to their information.
 * @param name The build rule name. (e.g. {@code java_library}).
 * @param ast The abstract syntax tree of the build rule function invocation.
 *///from  w w  w.j  a  va 2 s  . c o m
private void throwOnMissingRequiredAttribute(Map<String, Object> kwargs,
        ImmutableMap<String, ParamInfo> allParamInfo, String name, FuncallExpression ast) throws EvalException {
    ImmutableList<ParamInfo> missingAttributes = allParamInfo.values().stream()
            .filter(param -> !param.isOptional() && !kwargs.containsKey(param.getPythonName()))
            .collect(ImmutableList.toImmutableList());
    if (!missingAttributes.isEmpty()) {
        throw new EvalException(ast.getLocation(),
                name + " requires "
                        + missingAttributes.stream().map(ParamInfo::getPythonName)
                                .collect(Collectors.joining(" and "))
                        + " but they are not provided.",
                BUCK_RULE_DOC_URL_PREFIX + name);
    }
}

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

private ImmutableList<MessageAttachment> getMessageAttachments(MailboxSession session,
        ImmutableList<Attachment> attachments) throws MailboxException {
    ThrowingFunction<Attachment, MessageAttachment> toMessageAttachment = att -> messageAttachment(session,
            att);/*  w  w  w  .  ja v  a2 s.co  m*/
    return attachments.stream().map(Throwing.function(toMessageAttachment).sneakyThrow())
            .collect(Guavate.toImmutableList());
}

From source file:com.facebook.buck.features.rust.RustCompileUtils.java

private static RustCompileRule createBuild(BuildTarget target, String crateName,
        ProjectFilesystem projectFilesystem, BuildRuleParams params, ActionGraphBuilder graphBuilder,
        SourcePathRuleFinder ruleFinder, RustPlatform rustPlatform, RustBuckConfig rustConfig,
        ImmutableList<String> extraFlags, ImmutableList<String> extraLinkerFlags, Iterable<Arg> linkerInputs,
        CrateType crateType, Optional<String> edition, LinkableDepType depType, boolean rpath,
        ImmutableSortedSet<SourcePath> sources, SourcePath rootModule, boolean forceRlib, boolean preferStatic,
        Iterable<BuildRule> ruledeps, Optional<String> incremental) {
    CxxPlatform cxxPlatform = rustPlatform.getCxxPlatform();
    ImmutableList.Builder<Arg> linkerArgs = ImmutableList.builder();

    Optional<String> filename = crateType.filenameFor(target, crateName, cxxPlatform);

    if (crateType == CrateType.CDYLIB) {
        String soname = filename.get();
        Linker linker = cxxPlatform.getLd().resolve(graphBuilder);
        linkerArgs.addAll(StringArg.from(linker.soname(soname)));
    }/*from  w ww .  j  a  v  a 2  s . co m*/

    Stream.concat(rustPlatform.getLinkerArgs().stream(), extraLinkerFlags.stream()).filter(x -> !x.isEmpty())
            .map(StringArg::of).forEach(linkerArgs::add);

    linkerArgs.addAll(linkerInputs);

    ImmutableList.Builder<Arg> args = ImmutableList.builder();
    ImmutableList.Builder<Arg> depArgs = ImmutableList.builder();

    String relocModel;
    if (crateType.isPic()) {
        relocModel = "pic";
    } else {
        relocModel = "static";
    }

    Stream<String> checkArgs;
    if (crateType.isCheck()) {
        args.add(StringArg.of("--emit=metadata"));
        checkArgs = rustPlatform.getRustCheckFlags().stream();
    } else {
        checkArgs = Stream.of();
    }

    if (crateType.isSaveAnalysis()) {
        // This is an unstable option - not clear what the path to stabilization is.
        args.add(StringArg.of("-Zsave-analysis"));
    }

    Stream.of(Stream.of(String.format("--crate-name=%s", crateName),
            String.format("--crate-type=%s", crateType), String.format("-Crelocation-model=%s", relocModel)),
            extraFlags.stream(), checkArgs).flatMap(x -> x).map(StringArg::of).forEach(args::add);

    if (edition.isPresent()) {
        args.add(StringArg.of(String.format("--edition=%s", edition.get())));
    }

    if (incremental.isPresent()) {
        Path path = projectFilesystem.getBuckPaths().getTmpDir().resolve("rust-incremental")
                .resolve(incremental.get());

        for (Flavor f : target.getFlavors()) {
            path = path.resolve(f.getName());
        }
        args.add(StringArg.of(String.format("-Cincremental=%s", path)));
    }

    LinkableDepType rustDepType;
    // If we're building a CDYLIB then our Rust dependencies need to be static
    // Alternatively, if we're using forceRlib then anything else needs rlib deps.
    if (depType == LinkableDepType.SHARED && (forceRlib || crateType == CrateType.CDYLIB)) {
        rustDepType = LinkableDepType.STATIC_PIC;
    } else {
        rustDepType = depType;
    }

    // Find direct and transitive Rust deps. We do this in two passes, since a dependency that's
    // both direct and transitive needs to be listed on the command line in each form.
    //
    // This could end up with a lot of redundant parameters (lots of rlibs in one directory),
    // but Arg isn't comparable, so we can't put it in a Set.

    // First pass - direct deps
    RichStream.from(ruledeps).filter(RustLinkable.class::isInstance).map(
            rule -> ((RustLinkable) rule).getLinkerArg(true, crateType.isCheck(), rustPlatform, rustDepType))
            .forEach(depArgs::add);

    // Second pass - indirect deps
    new AbstractBreadthFirstTraversal<BuildRule>(RichStream.from(ruledeps).filter(RustLinkable.class)
            .flatMap(r -> RichStream.from(r.getRustLinakbleDeps(rustPlatform)))
            .collect(ImmutableList.toImmutableList())) {
        @Override
        public Iterable<BuildRule> visit(BuildRule rule) {
            Iterable<BuildRule> deps = ImmutableSortedSet.of();
            if (rule instanceof RustLinkable) {
                deps = ((RustLinkable) rule).getRustLinakbleDeps(rustPlatform);

                Arg arg = ((RustLinkable) rule).getLinkerArg(false, crateType.isCheck(), rustPlatform,
                        rustDepType);

                depArgs.add(arg);
            }
            return deps;
        }
    }.start();

    // A native crate output is no longer intended for consumption by the Rust toolchain;
    // it's either an executable, or a native library that C/C++ can link with. Rust DYLIBs
    // also need all dependencies available.
    if (crateType.needAllDeps()) {
        ImmutableList<Arg> nativeArgs = NativeLinkables
                .getTransitiveNativeLinkableInput(cxxPlatform, graphBuilder, ruledeps, depType,
                        r -> r instanceof RustLinkable
                                ? Optional.of(((RustLinkable) r).getRustLinakbleDeps(rustPlatform))
                                : Optional.empty())
                .getArgs();

        // Add necessary rpaths if we're dynamically linking with things
        if (rpath && depType == Linker.LinkableDepType.SHARED) {
            args.add(StringArg.of("-Crpath"));
        }

        linkerArgs.addAll(nativeArgs);
    }

    // If we want shared deps or are building a dynamic rlib, make sure we prefer
    // dynamic dependencies (esp to get dynamic dependency on standard libs)
    if ((!preferStatic && depType == Linker.LinkableDepType.SHARED) || crateType == CrateType.DYLIB) {
        args.add(StringArg.of("-Cprefer-dynamic"));
    }

    return RustCompileRule.from(ruleFinder, target, projectFilesystem, params, filename,
            rustPlatform.getRustCompiler().resolve(graphBuilder),
            rustPlatform.getLinkerProvider().resolve(graphBuilder), args.build(), depArgs.build(),
            linkerArgs.build(),
            CxxGenruleDescription.fixupSourcePaths(graphBuilder, ruleFinder, cxxPlatform, sources),
            CxxGenruleDescription.fixupSourcePath(graphBuilder, ruleFinder, cxxPlatform, rootModule),
            rustConfig.getRemapSrcPaths());
}

From source file:com.spectralogic.dsbrowser.gui.services.tasks.Ds3GetDataPoliciesTask.java

@Override
protected Optional<CreateBucketWithDataPoliciesModel> call() throws Exception {
    try {/*  w  w w. j  a va  2  s. co m*/
        final Ds3Client client = session.getClient();
        LOG.debug("Getting DataPolicies from [{}]", session.getEndpoint());
        final ImmutableList<CreateBucketModel> buckets = client
                .getDataPoliciesSpectraS3(new GetDataPoliciesSpectraS3Request()).getDataPolicyListResult()
                .getDataPolicies().stream()
                .map(bucket -> new CreateBucketModel(bucket.getName(), bucket.getId()))
                .collect(GuavaCollectors.immutableList());
        final ImmutableList<CreateBucketWithDataPoliciesModel> dataPoliciesList = buckets.stream()
                .map(policies -> new CreateBucketWithDataPoliciesModel(buckets, session, workers))
                .collect(GuavaCollectors.immutableList());

        LOG.debug("Found DataPolicies on [{}]", session.getEndpoint());
        loggingService.logMessage(resourceBundle.getString("dataPolicyRetrieved"), LogType.SUCCESS);

        final Optional<CreateBucketWithDataPoliciesModel> first = dataPoliciesList.stream().findFirst();
        return Optional.ofNullable(first.get());
    } catch (final Exception e) {
        LOG.error("Failed to get DataPolicies from " + session.getEndpoint(), e);
        loggingService.logMessage(resourceBundle.getString("dataPolicyNotFoundErr") + StringConstants.SPACE
                + session.getEndpoint() + StringConstants.SPACE + e, LogType.ERROR);
        throw e;
    }
}

From source file:codecrafter47.bungeetablistplus.tablistproviders.ConfigTablistProvider.java

public synchronized void update() {
    if (!active) {
        return;/*from  w  w w . j a  v a  2  s  . c  om*/
    }

    BungeeTabListPlus plugin = BungeeTabListPlus.getInstance();
    boolean canSeeHiddenPlayers = context.get(Context.KEY_VIEWER)
            .getOpt(MinecraftData.permission("bungeetablistplus.seevanished")).orElse(false);

    // PlayerSets
    ImmutableList<? extends IPlayer> all = ImmutableList.copyOf(
            Iterables.concat(Collections2.transform(plugin.playerProviders, IPlayerProvider::getPlayers)));
    for (Map.Entry<String, PlayerSet> entry : config.getPlayerSets().entrySet()) {
        PlayerVisibility hiddenPlayers = entry.getValue().getHiddenPlayers();
        List<Player> players = all.stream().map(p -> ((Player) p))
                .filter(player -> entry.getValue().getFilter()
                        .evaluate(context.derived().put(Context.KEY_PLAYER, player), ExpressionResult.BOOLEAN))
                .filter(player -> !BungeeTabListPlus.isHidden(player)
                        || (hiddenPlayers == PlayerVisibility.VISIBLE_TO_ADMINS && canSeeHiddenPlayers)
                        || hiddenPlayers == PlayerVisibility.VISIBLE)
                .collect(Collectors.toList());
        playerSets.put(entry.getKey(), players);
    }

    // Header & Footer
    if (config.isShowHeaderFooter()) {
        TextTemplate t;
        setHeader(null != (t = config.getHeader().get(headerIndex)) ? t.evaluate(context) : "");
        setFooter(null != (t = config.getFooter().get(footerIndex)) ? t.evaluate(context) : "");
    }
}

From source file:com.opengamma.strata.pricer.calibration.CurveCalibrator.java

private ImmutableMap<CurveName, JacobianCalibrationMatrix> updateJacobiansForGroup(
        ImmutableRatesProvider provider, ImmutableList<Trade> trades,
        ImmutableList<CurveParameterSize> orderGroup, ImmutableList<CurveParameterSize> orderPrev,
        ImmutableList<CurveParameterSize> orderAll,
        ImmutableMap<CurveName, JacobianCalibrationMatrix> jacobians) {

    // sensitivity to all parameters in the stated order
    int totalParamsAll = orderAll.stream().mapToInt(e -> e.getParameterCount()).sum();
    DoubleMatrix res = derivatives(trades, provider, orderAll, totalParamsAll);

    // jacobian direct
    int nbTrades = trades.size();
    int totalParamsGroup = orderGroup.stream().mapToInt(e -> e.getParameterCount()).sum();
    int totalParamsPrevious = totalParamsAll - totalParamsGroup;
    DoubleMatrix pDmCurrentMatrix = jacobianDirect(res, nbTrades, totalParamsGroup, totalParamsPrevious);

    // jacobian indirect: when totalParamsPrevious > 0
    DoubleMatrix pDmPrevious = jacobianIndirect(res, pDmCurrentMatrix, nbTrades, totalParamsGroup,
            totalParamsPrevious, orderPrev, jacobians);

    // add to the map of jacobians, one entry for each curve in this group
    ImmutableMap.Builder<CurveName, JacobianCalibrationMatrix> jacobianBuilder = ImmutableMap.builder();
    jacobianBuilder.putAll(jacobians);//from   w  w w.j a  v  a2 s. c om
    int startIndex = 0;
    for (CurveParameterSize order : orderGroup) {
        int paramCount = order.getParameterCount();
        double[][] pDmCurveArray = new double[paramCount][totalParamsAll];
        // copy data for previous groups
        if (totalParamsPrevious > 0) {
            for (int p = 0; p < paramCount; p++) {
                System.arraycopy(pDmPrevious.rowArray(startIndex + p), 0, pDmCurveArray[p], 0,
                        totalParamsPrevious);
            }
        }
        // copy data for this group
        for (int p = 0; p < paramCount; p++) {
            System.arraycopy(pDmCurrentMatrix.rowArray(startIndex + p), 0, pDmCurveArray[p],
                    totalParamsPrevious, totalParamsGroup);
        }
        // build final Jacobian matrix
        DoubleMatrix pDmCurveMatrix = DoubleMatrix.ofUnsafe(pDmCurveArray);
        jacobianBuilder.put(order.getName(), JacobianCalibrationMatrix.of(orderAll, pDmCurveMatrix));
        startIndex += paramCount;
    }
    return jacobianBuilder.build();
}

From source file:com.facebook.buck.core.config.BuckConfig.java

public ImmutableList<BuildTarget> getFullyQualifiedBuildTargets(String section, String key,
        TargetConfiguration targetConfiguration) {
    ImmutableList<String> buildTargets = getListWithoutComments(section, key);
    if (buildTargets.isEmpty()) {
        return ImmutableList.of();
    }/* ww  w.j  a v a  2  s .c o m*/
    return buildTargets.stream()
            .map(buildTarget -> getBuildTargetForFullyQualifiedTarget(buildTarget, targetConfiguration))
            .collect(ImmutableList.toImmutableList());
}

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  w  ww  .j  a v  a 2 s. 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.facebook.buck.cxx.CxxLibraryFactory.java

private static NativeLinkableInput getSharedLibraryNativeLinkTargetInput(BuildTarget buildTarget,
        ProjectFilesystem projectFilesystem, ActionGraphBuilder graphBuilder, SourcePathResolver pathResolver,
        SourcePathRuleFinder ruleFinder, CellPathResolver cellRoots, CxxBuckConfig cxxBuckConfig,
        CxxPlatform cxxPlatform, CxxLibraryDescriptionArg arg, ImmutableSet<BuildRule> deps,
        ImmutableList<StringWithMacros> linkerFlags, ImmutableList<StringWithMacros> exportedLinkerFlags,
        ImmutableList<StringWithMacros> postLinkerFlags,
        ImmutableList<StringWithMacros> postExportedLinkerFlags, ImmutableSet<FrameworkPath> frameworks,
        ImmutableSet<FrameworkPath> libraries,
        CxxLibraryDescription.TransitiveCxxPreprocessorInputFunction transitiveCxxPreprocessorInputFunction,
        Optional<CxxLibraryDescriptionDelegate> delegate) {

    // Create rules for compiling the PIC object files.
    ImmutableList<SourcePath> objects = requireObjects(buildTarget, projectFilesystem, graphBuilder,
            pathResolver, ruleFinder, cellRoots, cxxBuckConfig, cxxPlatform,
            cxxPlatform.getPicTypeForSharedLinking(), arg, deps, transitiveCxxPreprocessorInputFunction,
            delegate);// w  w  w  .jav  a 2 s .  com

    return NativeLinkableInput.builder()
            .addAllArgs(RichStream.<StringWithMacros>empty().concat(linkerFlags.stream())
                    .concat(exportedLinkerFlags.stream())
                    .map(f -> CxxDescriptionEnhancer.toStringWithMacrosArgs(buildTarget, cellRoots,
                            graphBuilder, cxxPlatform, f))
                    .toImmutableList())
            .addAllArgs(SourcePathArg.from(objects))
            .addAllArgs(RichStream.from(postLinkerFlags)
                    .map(f -> CxxDescriptionEnhancer.toStringWithMacrosArgs(buildTarget, cellRoots,
                            graphBuilder, cxxPlatform, f))
                    .toImmutableList())
            .addAllArgs(RichStream.from(postExportedLinkerFlags.stream())
                    .map(f -> CxxDescriptionEnhancer.toStringWithMacrosArgs(buildTarget, cellRoots,
                            graphBuilder, cxxPlatform, f))
                    .toImmutableList())
            .setFrameworks(frameworks).setLibraries(libraries).build();
}