List of usage examples for com.google.common.collect ImmutableList stream
default Stream<E> stream()
From source file:com.google.devtools.build.importdeps.ImportDepsChecker.java
public String computeResultOutput(String ruleLabel) { StringBuilder builder = new StringBuilder(); ImmutableList<String> missingClasses = resultCollector.getSortedMissingClassInternalNames(); for (String missing : missingClasses) { builder.append("Missing ").append(missing.replace('/', '.')).append('\n'); }/*from ww w .ja va 2s .c o m*/ ImmutableList<IncompleteState> incompleteClasses = resultCollector.getSortedIncompleteClasses(); for (IncompleteState incomplete : incompleteClasses) { builder.append("Incomplete ancestor classpath for ") .append(incomplete.classInfo().get().internalName().replace('/', '.')).append('\n'); ImmutableList<String> failurePath = incomplete.getResolutionFailurePath(); checkState(!failurePath.isEmpty(), "The resolution failure path is empty. %s", failurePath); builder.append(INDENT).append("missing ancestor: ") .append(failurePath.get(failurePath.size() - 1).replace('/', '.')).append('\n'); builder.append(INDENT).append("resolution failure path: ").append(failurePath.stream() .map(internalName -> internalName.replace('/', '.')).collect(Collectors.joining(" -> "))) .append('\n'); } ImmutableList<MissingMember> missingMembers = resultCollector.getSortedMissingMembers(); for (MissingMember missing : missingMembers) { builder.append("Missing member '").append(missing.memberName()).append("' in class ") .append(missing.owner().replace('/', '.')).append(" : name=").append(missing.memberName()) .append(", descriptor=").append(missing.descriptor()).append('\n'); } if (missingClasses.size() + incompleteClasses.size() + missingMembers.size() != 0) { builder.append("===Total===\n").append("missing=").append(missingClasses.size()).append('\n') .append("incomplete=").append(incompleteClasses.size()).append('\n').append("missing_members=") .append(missingMembers.size()).append('\n'); } ImmutableList<Path> indirectJars = resultCollector.getSortedIndirectDeps(); if (!indirectJars.isEmpty()) { ImmutableList<String> labels = extractLabels(indirectJars); if (ruleLabel.isEmpty() || labels.isEmpty()) { builder.append("*** Missing strict dependencies on the following Jars which don't carry " + "rule labels.\nPlease determine the originating rules, e.g., using Bazel's " + "'query' command, and add them to the dependencies of ") .append(ruleLabel.isEmpty() ? inputJars : ruleLabel).append('\n'); for (Path jar : indirectJars) { builder.append(jar).append('\n'); } } else { builder.append("*** Missing strict dependencies. Run the following command to fix ***\n\n"); builder.append(" add_dep "); for (String indirectLabel : labels) { builder.append(indirectLabel).append(" "); } builder.append(ruleLabel).append('\n'); } } return builder.toString(); }
From source file:com.spectralogic.ds3autogen.java.generators.requestmodels.BaseRequestGenerator.java
/** * Gets the list of with-constructors for all optional parameters *///from ww w . j av a2s. c o m @Override public ImmutableList<String> toWithConstructorList(final ImmutableList<Arguments> optionalParams, final String requestName, final Ds3DocSpec docSpec) { return optionalParams.stream().map(param -> toWithConstructor(param, requestName, docSpec)) .collect(GuavaCollectors.immutableList()); }
From source file:org.apache.james.jmap.methods.MIMEMessageConverter.java
private Multipart createMultipart(CreationMessage newMessage, ImmutableList<MessageAttachment> messageAttachments) { try {/*from w w w. j ava 2 s. co m*/ if (hasAttachment(messageAttachments)) { MultipartBuilder builder = MultipartBuilder.create(MIXED_SUB_TYPE); addBody(newMessage, builder); Consumer<MessageAttachment> addAttachment = addAttachment(builder); messageAttachments.stream().forEach(addAttachment); return builder.build(); } else { return createMultipartAlternativeBody(newMessage); } } catch (IOException e) { LOGGER.error("Error while creating textBody \n" + newMessage.getTextBody().get() + "\n or htmlBody \n" + newMessage.getHtmlBody().get(), e); throw Throwables.propagate(e); } }
From source file:com.opengamma.strata.pricer.credit.IsdaCompliantIndexCurveCalibrator.java
/** * Calibrates the index curve to the market data. * <p>/*from w w w .ja va 2 s . c om*/ * This creates the single credit curve for CDS index trades. * The curve nodes in {@code IsdaCreditCurveDefinition} must be CDS index. * <p> * The relevant discount curve and recovery rate curve must be stored in {@code ratesProvider}. * The day count convention for the resulting credit curve is the same as that of the discount curve. * * @param curveDefinition the curve definition * @param marketData the market data * @param ratesProvider the rates provider * @param refData the reference data * @return the index curve */ public LegalEntitySurvivalProbabilities calibrate(IsdaCreditCurveDefinition curveDefinition, MarketData marketData, ImmutableCreditRatesProvider ratesProvider, ReferenceData refData) { ArgChecker.isTrue(curveDefinition.getCurveValuationDate().equals(ratesProvider.getValuationDate()), "ratesProvider and curveDefinition must be based on the same valuation date"); ImmutableList<CdsIndexIsdaCreditCurveNode> curveNodes = curveDefinition.getCurveNodes().stream() .filter(n -> n instanceof CdsIndexIsdaCreditCurveNode).map(n -> (CdsIndexIsdaCreditCurveNode) n) .collect(Guavate.toImmutableList()); // Homogeneity of curveNode will be checked within IsdaCompliantCreditCurveCalibrator double indexFactor = computeIndexFactor(curveNodes.get(0), marketData); List<CdsIsdaCreditCurveNode> cdsNodes = curveNodes.stream().map(i -> toCdsNode(i)) .collect(Guavate.toImmutableList()); LegalEntitySurvivalProbabilities creditCurve = creditCurveCalibrator.calibrate(cdsNodes, curveDefinition.getName(), marketData, ratesProvider, curveDefinition.getDayCount(), curveDefinition.getCurrency(), curveDefinition.isComputeJacobian(), false, refData); NodalCurve underlyingCurve = ((IsdaCreditDiscountFactors) creditCurve.getSurvivalProbabilities()) .getCurve(); CurveMetadata metadata = underlyingCurve.getMetadata().withInfo(CurveInfoType.CDS_INDEX_FACTOR, indexFactor); if (curveDefinition.isStoreNodeTrade()) { int nNodes = curveDefinition.getCurveNodes().size(); ImmutableList<ParameterMetadata> parameterMetadata = IntStream.range(0, nNodes) .mapToObj(n -> ResolvedTradeParameterMetadata.of( curveNodes.get(n).trade(1d, marketData, refData).getUnderlyingTrade().resolve(refData), curveNodes.get(n).getLabel())) .collect(Guavate.toImmutableList()); metadata = metadata.withParameterMetadata(parameterMetadata); } NodalCurve curveWithFactor = underlyingCurve.withMetadata(metadata); return LegalEntitySurvivalProbabilities.of(creditCurve.getLegalEntityId(), IsdaCreditDiscountFactors .of(creditCurve.getCurrency(), creditCurve.getValuationDate(), curveWithFactor)); }
From source file:com.spectralogic.ds3autogen.java.generators.requestmodels.BaseRequestGenerator.java
/** * Gets the list of constructor models from a Ds3Request. For the base request, the * constructor list will be of size one. *//*from ww w . j ava 2s. c o m*/ @Override public ImmutableList<RequestConstructor> toConstructorList(final Ds3Request ds3Request, final String requestName, final Ds3DocSpec docSpec) { final ImmutableList<Arguments> constructorArgs = toConstructorArgumentsList(ds3Request); final ImmutableList<String> argNames = constructorArgs.stream().map(Arguments::getName) .collect(GuavaCollectors.immutableList()); final RequestConstructor constructor = new RequestConstructor(constructorArgs, constructorArgs, toQueryParamsList(ds3Request), toConstructorDocs(requestName, argNames, docSpec, 1)); return ImmutableList.of(constructor); }
From source file:com.opengamma.strata.pricer.curve.CurveCalibrator.java
private ImmutableMap<CurveName, JacobianCalibrationMatrix> updateJacobiansForGroup( ImmutableRatesProvider provider, ImmutableList<ResolvedTrade> 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);// w ww . java2s . co m 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.spectralogic.ds3autogen.net.generators.requestmodels.BaseRequestGenerator.java
/** * Creates the request constructors. There will be multiple constructors if there are * constructor parameters of type Guid/*from w w w . j av a 2s . com*/ */ @Override public ImmutableList<RequestConstructor> toConstructorList(final Ds3Request ds3Request, final String requestName, final Ds3DocSpec docSpec) { final ImmutableList<Arguments> constructorArgs = Helper .removeVoidArguments(toConstructorArgsList(ds3Request)); final ImmutableList<Arguments> queryParams = toQueryParamsList(ds3Request); final RequestConstructor standardConstructor = new RequestConstructor(constructorArgs, queryParams, ds3Request.getOperation(), toConstructorDocs(requestName, constructorArgs.stream().map(Arguments::getName).collect(GuavaCollectors.immutableList()), docSpec, 2)); return splitGuidConstructor(standardConstructor); }
From source file:org.apache.james.jmap.model.CreationMessage.java
private void assertAtLeastOneValidRecipient(ImmutableList.Builder<ValidationResult> errors) { ImmutableList<DraftEmailer> recipients = ImmutableList.<DraftEmailer>builder().addAll(to).addAll(cc) .addAll(bcc).build();// w w w . ja v a2 s . co m boolean hasAtLeastOneAddressToSendTo = recipients.stream().anyMatch(DraftEmailer::hasValidEmail); boolean recipientsHaveValidAddresses = recipients.stream().allMatch(e1 -> e1.getEmail() != null); if (!(recipientsHaveValidAddresses && hasAtLeastOneAddressToSendTo)) { errors.add(ValidationResult.builder().message("no recipient address set") .property(RECIPIENT_PROPERTY_NAMES).build()); } }
From source file:com.facebook.buck.versions.QueryTargetTranslator.java
@Override public Optional<Query> translateTargets(CellPathResolver cellPathResolver, String targetBaseName, TargetNodeTranslator translator, Query query) { // Extract all build targets from the original query string. ImmutableList<BuildTarget> targets; try {//from w w w . j a v a2s . com targets = QueryUtils.extractBuildTargets(cellPathResolver, targetBaseName, query) .collect(ImmutableList.toImmutableList()); } catch (QueryException e) { throw new RuntimeException("Error parsing/executing query from deps", e); } // If there's no targets, bail early. if (targets.isEmpty()) { return Optional.empty(); } // A pattern matching all of the build targets in the query string. Pattern targetsPattern = Pattern.compile( targets.stream().map(Object::toString).map(Pattern::quote).collect(Collectors.joining("|"))); // Build a new query string from the original by translating all build targets. String queryString = query.getQuery(); Matcher matcher = targetsPattern.matcher(queryString); StringBuilder builder = new StringBuilder(); int lastEnd = 0; while (matcher.find()) { builder.append(queryString, lastEnd, matcher.start()); BuildTarget target = unconfiguredBuildTargetFactory .createForBaseName(cellPathResolver, targetBaseName, matcher.group()) .configure(query.getTargetConfiguration()); Optional<BuildTarget> translated = translator.translate(cellPathResolver, targetBaseName, target); builder.append(translated.orElse(target).getFullyQualifiedName()); lastEnd = matcher.end(); } builder.append(queryString, lastEnd, queryString.length()); String newQuery = builder.toString(); return queryString.equals(newQuery) ? Optional.empty() : Optional.of(Query.of(newQuery, query.getTargetConfiguration(), query.getBaseName(), query.getResolvedQuery())); }
From source file:com.facebook.buck.ocaml.PrebuiltOcamlLibraryDescription.java
@Override public <A extends Arg> OcamlLibrary createBuildRule(TargetGraph targetGraph, final BuildRuleParams params, BuildRuleResolver resolver, final A args) { final BuildTarget target = params.getBuildTarget(); final boolean bytecodeOnly = args.bytecodeOnly.orElse(false); final String libDir = args.libDir.orElse("lib"); final String libName = args.libName.orElse(target.getShortName()); final String nativeLib = args.nativeLib.orElse(String.format("%s.cmxa", libName)); final String bytecodeLib = args.bytecodeLib.orElse(String.format("%s.cma", libName)); final ImmutableList<String> cLibs = args.cLibs; final Path libPath = target.getBasePath().resolve(libDir); final Path includeDir = libPath.resolve(args.includeDir.orElse("")); final Optional<SourcePath> staticNativeLibraryPath = bytecodeOnly ? Optional.empty() : Optional.of(new PathSourcePath(params.getProjectFilesystem(), libPath.resolve(nativeLib))); final SourcePath staticBytecodeLibraryPath = new PathSourcePath(params.getProjectFilesystem(), libPath.resolve(bytecodeLib)); final ImmutableList<SourcePath> staticCLibraryPaths = cLibs.stream() .map(input -> new PathSourcePath(params.getProjectFilesystem(), libPath.resolve(input))) .collect(MoreCollectors.toImmutableList()); final SourcePath bytecodeLibraryPath = new PathSourcePath(params.getProjectFilesystem(), libPath.resolve(bytecodeLib)); SourcePathRuleFinder ruleFinder = new SourcePathRuleFinder(resolver); SourcePathResolver pathResolver = new SourcePathResolver(ruleFinder); return new PrebuiltOcamlLibrary(params, pathResolver, ruleFinder, staticNativeLibraryPath, staticBytecodeLibraryPath, staticCLibraryPaths, bytecodeLibraryPath, libPath, includeDir); }