Java Code Examples for com.google.common.collect.ImmutableSortedSet#Builder
The following examples show how to use
com.google.common.collect.ImmutableSortedSet#Builder .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ParentChildIndexFieldData.java From Elasticsearch with Apache License 2.0 | 6 votes |
public ParentChildIndexFieldData(Index index, Settings indexSettings, MappedFieldType.Names fieldNames, FieldDataType fieldDataType, IndexFieldDataCache cache, MapperService mapperService, CircuitBreakerService breakerService) { super(index, indexSettings, fieldNames, fieldDataType, cache); this.breakerService = breakerService; if (Version.indexCreated(indexSettings).before(Version.V_2_0_0_beta1)) { parentTypes = new TreeSet<>(); for (DocumentMapper documentMapper : mapperService.docMappers(false)) { beforeCreate(documentMapper); } mapperService.addTypeListener(this); } else { ImmutableSortedSet.Builder<String> builder = ImmutableSortedSet.naturalOrder(); for (DocumentMapper mapper : mapperService.docMappers(false)) { ParentFieldMapper parentFieldMapper = mapper.parentFieldMapper(); if (parentFieldMapper.active()) { builder.add(parentFieldMapper.type()); } } parentTypes = builder.build(); } }
Example 2
Source File: ExternalPackageHelper.java From bazel with Apache License 2.0 | 6 votes |
/** * Returns directories, that should not be symlinked under the execroot. * * <p>Searches for toplevel_output_directories calls in the WORKSPACE file, and gathers values of * all "paths" attributes. */ public ImmutableSortedSet<String> getNotSymlinkedInExecrootDirectories(Environment env) throws InterruptedException { ImmutableSortedSet.Builder<String> builder = ImmutableSortedSet.naturalOrder(); WorkspaceFileValueProcessor gatherer = workspaceFileValue -> { ImmutableSortedSet<String> paths = workspaceFileValue.getDoNotSymlinkInExecrootPaths(); if (paths != null) { builder.addAll(paths); } // Continue to read all the fragments. return true; }; if (!iterateWorkspaceFragments(env, gatherer)) { return null; } return builder.build(); }
Example 3
Source File: AddressRangeAddressBookEntry.java From batfish with Apache License 2.0 | 6 votes |
/** * Converts a range of {@link Ip} addresses to a minimal set of {@link Prefix prefixes} that * exactly cover the range. */ @VisibleForTesting static SortedSet<IpWildcard> rangeToWildcards(Ip low, Ip high) { checkArgument(low.valid(), "Illegal range: %s is not a valid IP", low); checkArgument(high.valid(), "Illegal range: %s is not a valid IP", high); checkArgument(low.compareTo(high) <= 0, "Illegal range: %s is larger than %s", low, high); long lo = low.asLong(); long hi = high.asLong(); ImmutableSortedSet.Builder<IpWildcard> ret = ImmutableSortedSet.naturalOrder(); long start = lo; while (start <= hi) { long numIps = hi - start + 1; int minPrefixLengthThatStartsAtStart = 32 - Math.min(Long.numberOfTrailingZeros(start), 32); int minPrefixLengthContainedInRange = 32 - LongMath.log2(numIps, RoundingMode.DOWN); int prefixLengthToUse = Math.max(minPrefixLengthThatStartsAtStart, minPrefixLengthContainedInRange); ret.add(IpWildcard.create(Prefix.create(Ip.create(start), prefixLengthToUse))); start += 1L << (32 - prefixLengthToUse); } return ret.build(); }
Example 4
Source File: SwiftDescriptions.java From buck with Apache License 2.0 | 5 votes |
static ImmutableSortedSet<SourcePath> filterSwiftSources( SourcePathResolverAdapter sourcePathResolverAdapter, ImmutableSet<SourceWithFlags> srcs) { ImmutableSortedSet.Builder<SourcePath> swiftSrcsBuilder = ImmutableSortedSet.naturalOrder(); for (SourceWithFlags source : srcs) { if (isSwiftSource(source, sourcePathResolverAdapter)) { swiftSrcsBuilder.add(source.getSourcePath()); } } return swiftSrcsBuilder.build(); }
Example 5
Source File: TestCommand.java From buck with Apache License 2.0 | 5 votes |
@VisibleForTesting Iterable<TestRule> filterTestRules( BuckConfig buckConfig, ImmutableSet<BuildTarget> explicitBuildTargets, Iterable<TestRule> testRules) { ImmutableSortedSet.Builder<TestRule> builder = ImmutableSortedSet.orderedBy(Comparator.comparing(TestRule::getFullyQualifiedName)); for (TestRule rule : testRules) { boolean explicitArgument = explicitBuildTargets.contains(rule.getBuildTarget()); boolean matchesLabel = isMatchedByLabelOptions(buckConfig, rule.getLabels()); // We always want to run the rules that are given on the command line. Always. Unless we don't // want to. if (shouldExcludeWin() && !matchesLabel) { continue; } // The testRules Iterable contains transitive deps of the arguments given on the command line, // filter those out if such is the user's will. if (shouldExcludeTransitiveTests() && !explicitArgument) { continue; } // Normal behavior is to include all rules that match the given label as well as any that // were explicitly specified by the user. if (explicitArgument || matchesLabel) { builder.add(rule); } } return builder.build(); }
Example 6
Source File: AbstractNodeBuilder.java From buck with Apache License 2.0 | 5 votes |
@SuppressWarnings("unchecked") public ImmutableSortedSet<BuildTarget> findImplicitDeps() { ImplicitDepsInferringDescription<TArg> desc = (ImplicitDepsInferringDescription<TArg>) description; ImmutableSortedSet.Builder<BuildTarget> builder = ImmutableSortedSet.naturalOrder(); desc.findDepsForTargetFromConstructorArgs( target, cellRoots.getCellNameResolver(), getPopulatedArg(), builder, ImmutableSortedSet.naturalOrder()); return builder.build(); }
Example 7
Source File: FlowDiff.java From batfish with Apache License 2.0 | 5 votes |
/** * Helper method for flowDiffs and returnFlowDiffs, creates FlowDiffs given source and destination * IPs and ports of two flows */ private static SortedSet<FlowDiff> getFlowDiffs( Ip srcIp1, Ip dstIp1, Integer srcPort1, Integer dstPort1, Ip srcIp2, Ip dstIp2, Integer srcPort2, Integer dstPort2) { ImmutableSortedSet.Builder<FlowDiff> diffs = ImmutableSortedSet.naturalOrder(); if (dstPort1 != dstPort2) { diffs.add( new FlowDiff(PROP_DST_PORT, Integer.toString(dstPort1), Integer.toString(dstPort2))); } if (srcPort1 != srcPort2) { diffs.add( new FlowDiff(PROP_SRC_PORT, Integer.toString(srcPort1), Integer.toString(srcPort2))); } if (!dstIp1.equals(dstIp2)) { diffs.add(new FlowDiff(PROP_DST_IP, dstIp1.toString(), dstIp2.toString())); } if (!srcIp1.equals(srcIp2)) { diffs.add(new FlowDiff(PROP_SRC_IP, srcIp1.toString(), srcIp2.toString())); } return diffs.build(); }
Example 8
Source File: MapManager.java From Rails with GNU General Public License v2.0 | 5 votes |
public void configureFromXML(Tag tag) throws ConfigurationException { mapOrientation = MapOrientation.create(tag); List<Tag> hexTags = tag.getChildren("Hex"); ImmutableMap.Builder<MapHex.Coordinates, MapHex> hexBuilder = ImmutableMap.builder(); ImmutableSortedSet.Builder<Integer> tileCostsBuilder= ImmutableSortedSet.naturalOrder(); for (Tag hexTag : hexTags) { MapHex hex = MapHex.create(this, hexTag); hexBuilder.put(hex.getCoordinates(), hex); tileCostsBuilder.addAll(hex.getTileCostsList()); } hexes = hexBuilder.build(); possibleTileCosts = tileCostsBuilder.build(); minimum = MapHex.Coordinates.minimum(hexes.values()); maximum = MapHex.Coordinates.maximum(hexes.values()); // Default Stop Types Tag defaultsTag = tag.getChild("Defaults"); if (defaultsTag != null) { List<Tag> accessTags = defaultsTag.getChildren("Access"); defaultAccessTypes = Access.parseDefaults(this, accessTags); } // Map image attributes // FIXME: Move to an UI class Tag mapImageTag = tag.getChild("Image"); if (mapImageTag != null) { mapImageFilename = mapImageTag.getAttributeAsString("file"); mapXOffset = mapImageTag.getAttributeAsInteger("x", mapXOffset); mapYOffset = mapImageTag.getAttributeAsInteger("y", mapYOffset); mapScale = mapImageTag.getAttributeAsFloat("scale", mapScale); } }
Example 9
Source File: ConfigFeatureFlagTaggedTrimmingTransitionFactory.java From bazel with Apache License 2.0 | 5 votes |
@Override public PatchTransition create(Rule rule) { NonconfigurableAttributeMapper attrs = NonconfigurableAttributeMapper.of(rule); RuleClass ruleClass = rule.getRuleClassObject(); if (ruleClass.getName().equals(ConfigRuleClasses.ConfigFeatureFlagRule.RULE_NAME)) { return new ConfigFeatureFlagTaggedTrimmingTransition(ImmutableSortedSet.of(rule.getLabel())); } ImmutableSortedSet.Builder<Label> requiredLabelsBuilder = new ImmutableSortedSet.Builder<>(Ordering.natural()); if (attrs.isAttributeValueExplicitlySpecified(attributeName) && !attrs.get(attributeName, NODEP_LABEL_LIST).isEmpty()) { requiredLabelsBuilder.addAll(attrs.get(attributeName, NODEP_LABEL_LIST)); } if (ruleClass.getTransitionFactory() instanceof ConfigFeatureFlagTransitionFactory) { String settingAttribute = ((ConfigFeatureFlagTransitionFactory) ruleClass.getTransitionFactory()) .getAttributeName(); // Because the process of setting a flag also creates a dependency on that flag, we need to // include all the set flags, even if they aren't actually declared as used by this rule. requiredLabelsBuilder.addAll(attrs.get(settingAttribute, LABEL_KEYED_STRING_DICT).keySet()); } ImmutableSortedSet<Label> requiredLabels = requiredLabelsBuilder.build(); if (requiredLabels.isEmpty()) { return ConfigFeatureFlagTaggedTrimmingTransition.EMPTY; } return new ConfigFeatureFlagTaggedTrimmingTransition(requiredLabels); }
Example 10
Source File: CachingCalciteSchema.java From Bats with Apache License 2.0 | 5 votes |
protected void addImplicitTableToBuilder( ImmutableSortedSet.Builder<String> builder) { // Add implicit tables, case-sensitive. final long now = System.currentTimeMillis(); final NameSet set = implicitTableCache.get(now); builder.addAll(set.iterable()); }
Example 11
Source File: ElementCostOfDataStructures.java From memory-measurer with Apache License 2.0 | 5 votes |
public ImmutableSortedSet construct(int entries) { ImmutableSortedSet.Builder builder = ImmutableSortedSet.<Comparable>naturalOrder(); for (int i = 0; i < entries; i++) { builder.add(newEntry()); } return builder.build(); }
Example 12
Source File: SourceArtifactConverter.java From buck with Apache License 2.0 | 5 votes |
/** * @param srcs the set of the sources of a rule attribute * @param deps the {@link ProviderInfoCollection} from the dependencies of a rule * @return the {@link Artifact}s representing the sources. */ public static ImmutableSortedSet<Artifact> getArtifactsFromSrcs( Iterable<SourcePath> srcs, ImmutableMap<BuildTarget, ProviderInfoCollection> deps) { ImmutableSortedSet.Builder<Artifact> artifacts = ImmutableSortedSet.naturalOrder(); for (SourcePath src : srcs) { artifacts.add(SourceArtifactConverter.getArtifactsFromSrc(src, deps)); } return artifacts.build(); }
Example 13
Source File: ImmutableHolidayCalendar.java From Strata with Apache License 2.0 | 5 votes |
private Pair<ImmutableSortedSet<LocalDate>, ImmutableSortedSet<LocalDate>> getHolidaysAndWorkingDays() { if (startYear == 0) { return Pair.of(ImmutableSortedSet.of(), ImmutableSortedSet.of()); } ImmutableSortedSet.Builder<LocalDate> holidays = ImmutableSortedSet.naturalOrder(); ImmutableSortedSet.Builder<LocalDate> workingDays = ImmutableSortedSet.naturalOrder(); LocalDate firstOfMonth = LocalDate.of(startYear, 1, 1); for (int i = 0; i < lookup.length; i++) { int monthData = lookup[i]; int monthLen = firstOfMonth.lengthOfMonth(); int dow0 = firstOfMonth.getDayOfWeek().ordinal(); int bit = 1; for (int j = 0; j < monthLen; j++) { // if it is a holiday and not a weekend, then add the date if ((monthData & bit) == 0 && (weekends & (1 << dow0)) == 0) { holidays.add(firstOfMonth.withDayOfMonth(j + 1)); } // if it is a working day and a weekend, then add the date if ((monthData & bit) != 0 && (weekends & (1 << dow0)) != 0) { workingDays.add(firstOfMonth.withDayOfMonth(j + 1)); } dow0 = (dow0 + 1) % 7; bit <<= 1; } firstOfMonth = firstOfMonth.plusMonths(1); } return Pair.of(holidays.build(), workingDays.build()); }
Example 14
Source File: PlayerShareUtils.java From Rails with GNU General Public License v2.0 | 4 votes |
private static SortedSet<Integer> presidentSellMultiple(PublicCompany company, Player president) { // first: check what number of shares have to be dumped int presidentShareNumber = president.getPortfolioModel().getShare(company); PublicCertificate presidentCert = company.getPresidentsShare(); Player potential = company.findPlayerToDump(); int potentialShareNumber = potential.getPortfolioModel().getShare(company); int shareNumberDumpDifference = presidentShareNumber - potentialShareNumber; boolean presidentShareOnly = false; if (presidentCert.getShare() == presidentShareNumber) { // Only President Share to be sold... presidentShareOnly = true; } // ... if this is less than what the pool allows => goes back to non-president selling int poolAllows = poolAllowsShareNumbers(company); if ((shareNumberDumpDifference <= poolAllows) && (!presidentShareOnly)) { return otherSellMultiple(company, president); } // second: separate the portfolio into other shares and president certificate ImmutableList.Builder<PublicCertificate> otherCerts = ImmutableList.builder(); for (PublicCertificate c:president.getPortfolioModel().getCertificates(company)) { if (!c.isPresidentShare()) { otherCerts.add(c); } } // third: retrieve the share number combinations of the non-president certificates SortedSet<Integer> otherShareNumbers = CertificatesModel.shareNumberCombinations(otherCerts.build(), poolAllows); // fourth: combine pool and potential certificates, those are possible returns ImmutableList.Builder<PublicCertificate> returnCerts = ImmutableList.builder(); returnCerts.addAll(Bank.getPool(company).getPortfolioModel().getCertificates(company)); returnCerts.addAll(potential.getPortfolioModel().getCertificates(company)); SortedSet<Integer> returnShareNumbers = CertificatesModel.shareNumberCombinations(returnCerts.build(), presidentCert.getShares()); ImmutableSortedSet.Builder<Integer> sharesToSell = ImmutableSortedSet.naturalOrder(); for (Integer s:otherShareNumbers) { if (s <= shareNumberDumpDifference){ // shareNumber is below or equal the dump difference => add as possibility to sell without dump sharesToSell.add(s); } // now check if there are dumping possibilities for (int d=1; d <= presidentCert.getShares(); d++) { if (s+d <= poolAllows) { // d is the amount sold in addition to standard shares, returned has the remaining part of the president share int remaining = presidentCert.getShares() - d; if (returnShareNumbers.contains(remaining)) { sharesToSell.add(s+d); } } else { break; // pool is full } } } return sharesToSell.build(); }
Example 15
Source File: CxxDescriptionEnhancer.java From buck with Apache License 2.0 | 4 votes |
public static CxxLinkAndCompileRules createBuildRulesForCxxBinaryDescriptionArg( TargetGraph targetGraph, BuildTarget target, ProjectFilesystem projectFilesystem, ActionGraphBuilder graphBuilder, CellPathResolver cellRoots, CxxBuckConfig cxxBuckConfig, CxxPlatform cxxPlatform, CommonArg args, ImmutableSet<BuildTarget> extraDeps, Optional<StripStyle> stripStyle, Optional<LinkerMapMode> flavoredLinkerMapMode) { ImmutableMap<String, CxxSource> srcs = parseCxxSources(target, graphBuilder, cxxPlatform, args); ImmutableMap<Path, SourcePath> headers = parseHeaders(target, graphBuilder, projectFilesystem, Optional.of(cxxPlatform), args); // Build the binary deps. ImmutableSortedSet.Builder<BuildRule> depsBuilder = ImmutableSortedSet.naturalOrder(); // Add original declared and extra deps. args.getCxxDeps().get(graphBuilder, cxxPlatform).forEach(depsBuilder::add); // Add in deps found via deps query. ImmutableList<BuildRule> depQueryDeps = args.getDepsQuery().map(query -> Objects.requireNonNull(query.getResolvedQuery())) .orElse(ImmutableSortedSet.of()).stream() .map(graphBuilder::getRule) .collect(ImmutableList.toImmutableList()); depsBuilder.addAll(depQueryDeps); // Add any extra deps passed in. extraDeps.stream().map(graphBuilder::getRule).forEach(depsBuilder::add); ImmutableSortedSet<BuildRule> deps = depsBuilder.build(); CxxLinkOptions linkOptions = CxxLinkOptions.of( args.getThinLto(), args.getFatLto() ); Optional<LinkableListFilter> linkableListFilter = LinkableListFilterFactory.from(cxxBuckConfig, args, targetGraph); return createBuildRulesForCxxBinary( target, projectFilesystem, graphBuilder, cellRoots, cxxBuckConfig, cxxPlatform, srcs, headers, deps, args.getLinkDepsQueryWhole() ? RichStream.from(depQueryDeps).map(BuildRule::getBuildTarget).toImmutableSet() : ImmutableSet.of(), stripStyle, flavoredLinkerMapMode, args.getLinkStyle().orElse(Linker.LinkableDepType.STATIC), linkableListFilter, linkOptions, args.getPreprocessorFlags(), args.getPlatformPreprocessorFlags(), args.getLangPreprocessorFlags(), args.getLangPlatformPreprocessorFlags(), args.getFrameworks(), args.getLibraries(), args.getCompilerFlags(), args.getLangCompilerFlags(), args.getPlatformCompilerFlags(), args.getLangPlatformCompilerFlags(), args.getPrefixHeader(), args.getPrecompiledHeader(), args.getLinkerFlags(), args.getLinkerExtraOutputs(), args.getPlatformLinkerFlags(), args.getCxxRuntimeType(), args.getRawHeaders(), args.getIncludeDirectories(), args.getExecutableName()); }
Example 16
Source File: DnsServiceEndpointGroup.java From armeria with Apache License 2.0 | 4 votes |
@Override ImmutableSortedSet<Endpoint> onDnsRecords(List<DnsRecord> records, int ttl) throws Exception { final ImmutableSortedSet.Builder<Endpoint> builder = ImmutableSortedSet.naturalOrder(); for (DnsRecord r : records) { if (!(r instanceof DnsRawRecord) || r.type() != DnsRecordType.SRV) { continue; } final ByteBuf content = ((ByteBufHolder) r).content(); if (content.readableBytes() <= 6) { // Too few bytes warnInvalidRecord(DnsRecordType.SRV, content); continue; } content.markReaderIndex(); content.skipBytes(2); // priority unused final int weight = content.readUnsignedShort(); final int port = content.readUnsignedShort(); final Endpoint endpoint; try { final String target = stripTrailingDot(DefaultDnsRecordDecoder.decodeName(content)); endpoint = port > 0 ? Endpoint.of(target, port) : Endpoint.of(target); } catch (Exception e) { content.resetReaderIndex(); warnInvalidRecord(DnsRecordType.SRV, content); continue; } builder.add(endpoint.withWeight(weight)); } final ImmutableSortedSet<Endpoint> endpoints = builder.build(); if (logger().isDebugEnabled()) { logger().debug("{} Resolved: {} (TTL: {})", logPrefix(), endpoints.stream() .map(e -> e.authority() + '/' + e.weight()) .collect(Collectors.joining(", ")), ttl); } return endpoints; }
Example 17
Source File: AbstractSourcePathResolver.java From buck with Apache License 2.0 | 4 votes |
private ImmutableSortedSet<Path> getPathsPrivateImpl(ImmutableSortedSet<SourcePath> sourcePaths) { ImmutableSortedSet.Builder<Path> pathsBuilder = ImmutableSortedSet.naturalOrder(); sourcePaths.forEach(sourcePath -> pathsBuilder.addAll(getPathPrivateImpl(sourcePath))); return pathsBuilder.build(); }
Example 18
Source File: AggregateCommandLineArgsTest.java From buck with Apache License 2.0 | 4 votes |
@Test public void returnsProperStreamAndArgCount() throws EvalException { FakeProjectFilesystem filesystem = new FakeProjectFilesystem(); Artifact path1 = SourceArtifactImpl.of(PathSourcePath.of(filesystem, Paths.get("some_bin"))); Artifact path2 = SourceArtifactImpl.of(PathSourcePath.of(filesystem, Paths.get("other_file"))); BuildTarget target = BuildTargetFactory.newInstance("//:some_rule"); ActionRegistryForTests registry = new ActionRegistryForTests(target, filesystem); Artifact artifact3 = registry.declareArtifact(Paths.get("out.txt"), Location.BUILTIN); OutputArtifact artifact3Output = (OutputArtifact) artifact3.asSkylarkOutputArtifact(Location.BUILTIN); Path artifact3Path = BuildPaths.getGenDir(filesystem, target).resolve("out.txt"); CommandLineArgs args = new AggregateCommandLineArgs( ImmutableList.of( createRunInfo(ImmutableSortedMap.of("FOO", "foo_val"), ImmutableList.of(path1)), createRunInfo(ImmutableSortedMap.of("BAZ", "baz_val"), ImmutableList.of(path2, 1)), CommandLineArgsFactory.from(ImmutableList.of("foo", "bar", artifact3Output)))); new WriteAction( registry, ImmutableSortedSet.of(), ImmutableSortedSet.of(artifact3Output), "contents", false); CommandLine cli = new ExecCompatibleCommandLineBuilder(new ArtifactFilesystem(filesystem)).build(args); assertEquals( ImmutableList.of( filesystem.resolve("some_bin").toAbsolutePath().toString(), "other_file", "1", "foo", "bar", artifact3Path.toString()), cli.getCommandLineArgs()); assertEquals(6, args.getEstimatedArgsCount()); assertEquals( ImmutableSortedMap.of("FOO", "foo_val", "BAZ", "baz_val"), cli.getEnvironmentVariables()); ImmutableSortedSet.Builder<Artifact> inputs = ImmutableSortedSet.naturalOrder(); ImmutableSortedSet.Builder<OutputArtifact> outputs = ImmutableSortedSet.naturalOrder(); args.visitInputsAndOutputs(inputs::add, outputs::add); assertEquals(ImmutableSortedSet.of(path1, path2), inputs.build()); assertEquals(ImmutableSortedSet.of(artifact3Output), outputs.build()); }
Example 19
Source File: CachingCalciteSchema.java From calcite with Apache License 2.0 | 4 votes |
protected void addImplicitTypeNamesToBuilder(ImmutableSortedSet.Builder<String> builder) { // Add implicit types, case-sensitive. final long now = System.currentTimeMillis(); final NameSet set = implicitTypeCache.get(now); builder.addAll(set.iterable()); }
Example 20
Source File: CiscoNxosConfiguration.java From batfish with Apache License 2.0 | 4 votes |
private void createOspfExportPolicy( OspfProcess proc, String processName, String vrfName, org.batfish.datamodel.ospf.OspfProcess.Builder builder) { ImmutableList.Builder<Statement> exportStatementsBuilder = ImmutableList.builder(); ImmutableSortedSet.Builder<String> exportPolicySourcesBuilder = ImmutableSortedSet.naturalOrder(); OspfDefaultOriginate defaultOriginate = proc.getDefaultOriginate(); // First try redistributing static routes, which may include default route Optional.ofNullable(proc.getRedistributionPolicy(RoutingProtocolInstance.staticc())) .map(RedistributionPolicy::getRouteMap) .filter(_c.getRoutingPolicies()::containsKey) .ifPresent( routeMapName -> { exportPolicySourcesBuilder.add(routeMapName); exportStatementsBuilder.add( new If( new MatchProtocol(RoutingProtocol.STATIC), ImmutableList.of(call(routeMapName)))); }); // Then try originating default route (either always or from RIB route not covered above) if (defaultOriginate != null) { BooleanExpr guard; if (defaultOriginate.getAlways()) { builder.setGeneratedRoutes( ImmutableSortedSet.of(GeneratedRoute.builder().setNetwork(Prefix.ZERO).build())); guard = new Conjunction( ImmutableList.<BooleanExpr>builder() .add(matchDefaultRoute()) .add(new MatchProtocol(RoutingProtocol.AGGREGATE)) .build()); } else { guard = matchDefaultRoute(); } ImmutableList.Builder<Statement> defaultOriginateStatements = ImmutableList.builder(); Optional.ofNullable(defaultOriginate.getRouteMap()) .filter(_c.getRoutingPolicies()::containsKey) .ifPresent( defaultOriginateRouteMapName -> { exportPolicySourcesBuilder.add(defaultOriginateRouteMapName); defaultOriginateStatements.add(call(defaultOriginateRouteMapName)); }); defaultOriginateStatements.add(Statements.ExitAccept.toStaticStatement()); exportStatementsBuilder.add(new If(guard, defaultOriginateStatements.build())); } // Then try remaining redistribution policies Optional.ofNullable(proc.getRedistributionPolicy(RoutingProtocolInstance.direct())) .map(RedistributionPolicy::getRouteMap) .filter(_c.getRoutingPolicies()::containsKey) .ifPresent( routeMapName -> { exportPolicySourcesBuilder.add(routeMapName); exportStatementsBuilder.add( new If( new MatchProtocol(RoutingProtocol.CONNECTED), ImmutableList.of(call(routeMapName)))); }); List<Statement> exportInnerStatements = exportStatementsBuilder.build(); int defaultRedistributionMetric = proc.getAreas().isEmpty() ? OspfArea.DEFAULT_DEFAULT_COST : proc.getAreas().values().iterator().next().getDefaultCost(); if (!proc.getAreas().values().stream() .map(OspfArea::getDefaultCost) .allMatch(Predicates.equalTo(defaultRedistributionMetric))) { _w.unimplemented( String.format( "Unimplemented: OSPF process '%s': non-uniform default-cost across areas", processName)); return; } if (exportInnerStatements.isEmpty()) { // nothing to export return; } String exportPolicyName = computeOspfExportPolicyName(processName, vrfName); RoutingPolicy exportPolicy = RoutingPolicy.builder() .setName(exportPolicyName) .setOwner(_c) .setStatements( ImmutableList.<Statement>builder() .add(new SetOspfMetricType(OspfMetricType.E1)) .add(new SetMetric(new LiteralLong(defaultRedistributionMetric))) .addAll(exportStatementsBuilder.build()) .add(Statements.ExitReject.toStaticStatement()) .build()) .build(); builder.setExportPolicy(exportPolicy); builder.setExportPolicySources(exportPolicySourcesBuilder.build()); return; }