Java Code Examples for com.google.common.collect.ImmutableSortedMap#naturalOrder()

The following examples show how to use com.google.common.collect.ImmutableSortedMap#naturalOrder() . 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: FindMatchingFilterLinesAnswerer.java    From batfish with Apache License 2.0 6 votes vote down vote up
/**
 * Returns a map of line index in {@code aclLines} to behavior to report for that line. Only
 * includes lines that should be reported.
 */
@VisibleForTesting
static SortedMap<Integer, LineBehavior> getBehaviorToReport(
    List<AclLine> aclLines,
    BDD headerSpaceBdd,
    IpAccessListToBdd bddConverter,
    @Nullable Action action) {
  LineBehaviorFinder behaviorFinder =
      new LineBehaviorFinder(bddConverter, action, headerSpaceBdd);
  ImmutableSortedMap.Builder<Integer, LineBehavior> actionsToReport =
      ImmutableSortedMap.naturalOrder();
  for (int i = 0; i < aclLines.size(); i++) {
    LineBehavior lineBehavior = behaviorFinder.visit(aclLines.get(i));
    if (lineBehavior != null) {
      actionsToReport.put(i, lineBehavior);
    }
  }
  return actionsToReport.build();
}
 
Example 2
Source File: RustCompileUtils.java    From buck with Apache License 2.0 5 votes vote down vote up
/**
 * Collect all the shared libraries generated by {@link RustLinkable}s found by transitively
 * traversing all unbroken dependency chains of {@link
 * com.facebook.buck.features.rust.RustLinkable} objects found via the passed in {@link BuildRule}
 * roots.
 *
 * @return a mapping of library name to the library {@link SourcePath}.
 */
public static Map<String, SourcePath> getTransitiveRustSharedLibraries(
    RustPlatform rustPlatform, Iterable<? extends BuildRule> inputs, boolean forceRlib) {
  ImmutableSortedMap.Builder<String, SourcePath> libs = ImmutableSortedMap.naturalOrder();

  new AbstractBreadthFirstTraversal<BuildRule>(inputs) {
    @Override
    public Iterable<BuildRule> visit(BuildRule rule) {
      Iterable<BuildRule> deps = ImmutableSet.of();
      if (rule instanceof RustLinkable) {
        RustLinkable rustLinkable = (RustLinkable) rule;

        if (!rustLinkable.isProcMacro()) {
          deps = rustLinkable.getRustLinakbleDeps(rustPlatform);

          if (!forceRlib
              && rustLinkable.getPreferredLinkage() != NativeLinkableGroup.Linkage.STATIC) {
            libs.putAll(rustLinkable.getRustSharedLibraries(rustPlatform));
          }
        }
      }
      return deps;
    }
  }.start();

  return libs.build();
}
 
Example 3
Source File: ElementCostOfDataStructures.java    From memory-measurer with Apache License 2.0 5 votes vote down vote up
public ImmutableSortedMap construct(int entries) {
  ImmutableSortedMap.Builder builder = ImmutableSortedMap.<Comparable, Object>naturalOrder();
  for (int i = 0; i < entries; i++) {
    builder.put(newEntry(), newEntry());
  }
  return builder.build();
}
 
Example 4
Source File: Node.java    From batfish with Apache License 2.0 5 votes vote down vote up
/**
 * Create a new node based on the configuration. Initializes virtual routers based on {@link
 * Configuration} VRFs.
 *
 * @param configuration the {@link Configuration} backing this node
 */
public Node(@Nonnull Configuration configuration) {
  _c = configuration;
  ImmutableSortedMap.Builder<String, VirtualRouter> b = ImmutableSortedMap.naturalOrder();
  for (String vrfName : _c.getVrfs().keySet()) {
    VirtualRouter vr = new VirtualRouter(vrfName, this);
    b.put(vrfName, vr);
  }
  _virtualRouters = b.build();
}
 
Example 5
Source File: NinjaTarget.java    From bazel with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a map from rule variable to fully-expanded value, for all rule variables defined in
 * this target.
 */
public ImmutableSortedMap<NinjaRuleVariable, String> computeRuleVariables() {
  ImmutableSortedMap<String, String> lateExpansionVariables = computeInputOutputVariables();
  ImmutableSortedMap.Builder<String, String> fullExpansionVariablesBuilder =
      ImmutableSortedMap.<String, String>naturalOrder().putAll(lateExpansionVariables);

  ImmutableSortedMap.Builder<NinjaRuleVariable, String> builder =
      ImmutableSortedMap.naturalOrder();
  for (Map.Entry<NinjaRuleVariable, NinjaVariableValue> entry : ruleVariables.entrySet()) {
    NinjaRuleVariable type = entry.getKey();
    // Skip command for now. It may need to expand other rule variables.
    if (NinjaRuleVariable.COMMAND.equals(type)) {
      continue;
    }

    String expandedValue = entry.getValue().expandValue(lateExpansionVariables);
    builder.put(type, expandedValue);
    fullExpansionVariablesBuilder.put(Ascii.toLowerCase(type.name()), expandedValue);
  }

  // TODO(cparsons): Ensure parsing exception is thrown early if the rule has no command defined.
  // Otherwise, this throws NPE.
  String expandedCommand =
      ruleVariables
          .get(NinjaRuleVariable.COMMAND)
          .expandValue(fullExpansionVariablesBuilder.build());
  builder.put(NinjaRuleVariable.COMMAND, expandedCommand);
  return builder.build();
}
 
Example 6
Source File: JdbcEntryData.java    From incubator-gobblin with Apache License 2.0 5 votes vote down vote up
public JdbcEntryData(Iterable<JdbcEntryDatum> jdbcEntryDatumEntries) {
  Preconditions.checkNotNull(jdbcEntryDatumEntries);
  ImmutableMap.Builder<String, JdbcEntryDatum> builder = ImmutableSortedMap.naturalOrder();
  for (JdbcEntryDatum datum : jdbcEntryDatumEntries) {
    builder.put(datum.getColumnName(), datum);
  }
  this.jdbcEntryData = builder.build();
}
 
Example 7
Source File: FirefoxOptions.java    From selenium with Apache License 2.0 5 votes vote down vote up
@Override
public Map<String, Object> asMap() {
  Map<String, Object> toReturn = new HashMap<>(super.asMap());

  ImmutableSortedMap.Builder<String, Object> w3cOptions = ImmutableSortedMap.naturalOrder();
  w3cOptions.put("args", unmodifiableList(new ArrayList<>(args)));

  if (binary != null) {
    w3cOptions.put("binary", binary.asPath());
  }

  if (logLevel != null) {
    w3cOptions.put("log", singletonMap("level", logLevel));
  }

  if (profile != null) {
    preferences.forEach(profile::setPreference);
    try {
      w3cOptions.put("profile", profile.toJson());
    } catch (IOException e) {
      throw new WebDriverException(e);
    }
  } else {
    w3cOptions.put("prefs", unmodifiableMap(new HashMap<>(preferences)));
  }

  toReturn.put(FIREFOX_OPTIONS, w3cOptions.build());

  return unmodifiableMap(toReturn);
}
 
Example 8
Source File: SymlinkMap.java    From buck with Apache License 2.0 5 votes vote down vote up
private ImmutableSortedMap<String, NonHashableSourcePathContainer> getLinksForRuleKey() {
  ImmutableSortedMap.Builder<String, NonHashableSourcePathContainer> linksForRuleKeyBuilder =
      ImmutableSortedMap.naturalOrder();
  for (Map.Entry<Path, SourcePath> entry : links.entrySet()) {
    linksForRuleKeyBuilder.put(
        entry.getKey().toString(), new NonHashableSourcePathContainer(entry.getValue()));
  }
  return linksForRuleKeyBuilder.build();
}
 
Example 9
Source File: EncodedConfigParser.java    From exhibitor with Apache License 2.0 5 votes vote down vote up
/**
 * Return a sorted map of the fields/values
 *
 * @return map
 */
public Map<String, String> getSortedMap()
{
    ImmutableSortedMap.Builder<String, String> builder = ImmutableSortedMap.naturalOrder();
    for ( FieldValue fv : fieldValues )
    {
        builder.put(fv.getField(), fv.getValue());
    }

    return builder.build();
}
 
Example 10
Source File: SortedMapTypeCoercer.java    From buck with Apache License 2.0 5 votes vote down vote up
@Override
public ImmutableSortedMap<K, V> coerce(
    CellNameResolver cellRoots,
    ProjectFilesystem filesystem,
    ForwardRelativePath pathRelativeToProjectRoot,
    TargetConfiguration targetConfiguration,
    TargetConfiguration hostConfiguration,
    ImmutableSortedMap<KU, VU> object)
    throws CoerceFailedException {
  ImmutableSortedMap.Builder<K, V> builder = ImmutableSortedMap.naturalOrder();

  for (Map.Entry<KU, VU> entry : object.entrySet()) {
    K key =
        keyTypeCoercer.coerce(
            cellRoots,
            filesystem,
            pathRelativeToProjectRoot,
            targetConfiguration,
            hostConfiguration,
            entry.getKey());
    V value =
        valueTypeCoercer.coerce(
            cellRoots,
            filesystem,
            pathRelativeToProjectRoot,
            targetConfiguration,
            hostConfiguration,
            entry.getValue());
    builder.put(key, value);
  }

  return builder.build();
}
 
Example 11
Source File: Match.java    From Bats with Apache License 2.0 5 votes vote down vote up
/** Creates an immutable map of a map of sorted sets. */
private static <K extends Comparable<K>, V> ImmutableSortedMap<K, SortedSet<V>> copyMap(
        Map<K, ? extends SortedSet<V>> map) {
    final ImmutableSortedMap.Builder<K, SortedSet<V>> b = ImmutableSortedMap.naturalOrder();
    for (Map.Entry<K, ? extends SortedSet<V>> e : map.entrySet()) {
        b.put(e.getKey(), ImmutableSortedSet.copyOf(e.getValue()));
    }
    return b.build();
}
 
Example 12
Source File: PythonUtil.java    From buck with Apache License 2.0 5 votes vote down vote up
public static ImmutableSortedMap<Path, SourcePath> parseModules(
    BuildTarget target,
    ActionGraphBuilder graphBuilder,
    PythonPlatform pythonPlatform,
    CxxPlatform cxxPlatform,
    Optional<ImmutableMap<BuildTarget, Version>> versions,
    PythonLibraryDescription.CoreArg args) {
  ImmutableSortedMap.Builder<Path, SourcePath> builder = ImmutableSortedMap.naturalOrder();
  forEachSrc(target, graphBuilder, pythonPlatform, cxxPlatform, versions, args, builder::put);
  return builder.build();
}
 
Example 13
Source File: NinjaTarget.java    From bazel with Apache License 2.0 5 votes vote down vote up
/**
 * We expand the rule's variables with the following assumptions: Rule variables can refer to
 * target's variables (and file variables). Interdependence between rule variables can happen
 * only for 'command' variable, for now we ignore other possible dependencies between rule
 * variables (seems the only other variable which can meaningfully depend on sibling variables
 * is description, and currently we are ignoring it).
 *
 * <p>Also, for resolving rule's variables we are using scope+offset of target, according to
 * specification (https://ninja-build.org/manual.html#_variable_expansion).
 *
 * <p>See {@link NinjaRuleVariable} for the list.
 */
private static ImmutableSortedMap<NinjaRuleVariable, NinjaVariableValue> reduceRuleVariables(
    NinjaScope targetScope,
    long targetOffset,
    Map<NinjaRuleVariable, NinjaVariableValue> ruleVariables,
    ImmutableSortedMap<String, String> targetVariables,
    Interner<String> interner) {
  ImmutableSortedMap.Builder<String, List<Pair<Long, String>>> variablesBuilder =
      ImmutableSortedMap.naturalOrder();
  targetVariables.forEach(
      (key, value) -> variablesBuilder.put(key, ImmutableList.of(Pair.of(0L, value))));
  NinjaScope scopeWithVariables =
      targetScope.createScopeFromExpandedValues(variablesBuilder.build());

  ImmutableSortedMap.Builder<NinjaRuleVariable, NinjaVariableValue> builder =
      ImmutableSortedMap.naturalOrder();

  // Description is taken from the "build" statement (instead of the referenced rule)
  // if it's available.
  boolean targetHasDescription = false;
  String targetVariable = targetVariables.get("description");
  if (targetVariable != null) {
    builder.put(
        NinjaRuleVariable.DESCRIPTION, NinjaVariableValue.createPlainText(targetVariable));
    targetHasDescription = true;
  }

  for (Map.Entry<NinjaRuleVariable, NinjaVariableValue> entry : ruleVariables.entrySet()) {
    NinjaRuleVariable type = entry.getKey();
    if (type.equals(NinjaRuleVariable.DESCRIPTION) && targetHasDescription) {
      // Don't use the rule description, as the target defined a specific description.
      continue;
    }
    NinjaVariableValue reducedValue =
        scopeWithVariables.getReducedValue(
            targetOffset, entry.getValue(), INPUTS_OUTPUTS_VARIABLES, interner);
    builder.put(type, reducedValue);
  }
  return builder.build();
}
 
Example 14
Source File: CompiledRoutes.java    From xrpc with Apache License 2.0 5 votes vote down vote up
/**
 * Returns compiled routes built from the given route map.
 *
 * @param metricRegistry the registry to generate per-(route,method) rate statistics in
 */
public CompiledRoutes(
    Map<RoutePath, Map<HttpMethod, Handler>> rawRoutes, MetricRegistry metricRegistry) {
  // Build a sorted map of the routes.
  ImmutableSortedMap.Builder<RoutePath, ImmutableMap<HttpMethod, Handler>> routesBuilder =
      ImmutableSortedMap.naturalOrder();
  for (Map.Entry<RoutePath, Map<HttpMethod, Handler>> routeEntry : rawRoutes.entrySet()) {
    ImmutableMap.Builder<HttpMethod, Handler> handlers = new ImmutableMap.Builder<>();
    RoutePath route = routeEntry.getKey();
    for (Map.Entry<HttpMethod, Handler> methodHandlerEntry : routeEntry.getValue().entrySet()) {
      HttpMethod method = methodHandlerEntry.getKey();

      // Wrap the user-provided handler in one that tracks request rates.
      String metricName = MetricRegistry.name("routes", method.name(), route.toString());
      String timerName = MetricRegistry.name("routeLatency", method.name(), route.toString());
      final Handler userHandler = methodHandlerEntry.getValue();
      final Meter meter = metricRegistry.meter(metricName);
      final Timer timer = metricRegistry.timer(timerName);

      // TODO (AD): Pull this out into an adapted handler in a separate class.
      Handler adaptedHandler =
          request -> {
            meter.mark();
            try {
              return timer.time(() -> userHandler.handle(request));
            } catch (Exception e) {
              return request.connectionContext().exceptionHandler().handle(request, e);
            }
          };
      handlers.put(method, adaptedHandler);
    }

    routesBuilder.put(route, handlers.build());
  }

  this.routes = routesBuilder.build();
}
 
Example 15
Source File: NinjaTarget.java    From bazel with Apache License 2.0 5 votes vote down vote up
private ImmutableSortedMap<String, String> computeInputOutputVariables() {
  ImmutableSortedMap.Builder<String, String> builder = ImmutableSortedMap.naturalOrder();
  String inNewline =
      inputs.get(InputKind.EXPLICIT).stream()
          .map(PathFragment::getPathString)
          .collect(Collectors.joining("\n"));
  String out =
      outputs.get(OutputKind.EXPLICIT).stream()
          .map(PathFragment::getPathString)
          .collect(Collectors.joining(" "));
  builder.put("in", inNewline.replace('\n', ' '));
  builder.put("in_newline", inNewline);
  builder.put("out", out);
  return builder.build();
}
 
Example 16
Source File: SwiftAttributeParser.java    From buck with Apache License 2.0 5 votes vote down vote up
private ImmutableMap<Path, Path> getPublicHeaderMapEntries(
    TargetNode<? extends CxxLibraryDescription.CommonArg> node,
    boolean hasSwiftVersionArg,
    String objCbjCGeneratedHeaderName) {
  if (!hasSwiftVersionArg) {
    return ImmutableMap.of();
  }

  Optional<TargetNode<AppleNativeTargetDescriptionArg>> maybeAppleNode =
      TargetNodes.castArg(node, AppleNativeTargetDescriptionArg.class);
  if (!maybeAppleNode.isPresent()) {
    return ImmutableMap.of();
  }

  TargetNode<? extends AppleNativeTargetDescriptionArg> appleNode = maybeAppleNode.get();
  if (!projectGenerationStateCache.targetContainsSwiftSourceCode(appleNode)) {
    return ImmutableMap.of();
  }

  BuildTarget buildTarget = appleNode.getBuildTarget();
  Path headerPrefix =
      AppleDescriptions.getHeaderPathPrefix(appleNode.getConstructorArg(), buildTarget);
  Path relativePath = headerPrefix.resolve(objCbjCGeneratedHeaderName);

  ImmutableSortedMap.Builder<Path, Path> builder = ImmutableSortedMap.naturalOrder();
  builder.put(
      relativePath,
      getSwiftObjCGeneratedHeaderPath(appleNode, objCbjCGeneratedHeaderName).toAbsolutePath());

  return builder.build();
}
 
Example 17
Source File: CiscoXrConversions.java    From batfish with Apache License 2.0 4 votes vote down vote up
/**
 * Converts a {@link CryptoMapEntry} to an {@link IpsecPhase2Policy} and a list of {@link
 * IpsecPeerConfig}
 */
private static void convertCryptoMapEntry(
    final Configuration c,
    CryptoMapEntry cryptoMapEntry,
    String cryptoMapNameSeqNumber,
    String cryptoMapName,
    Warnings w) {
  // skipping incomplete static or dynamic crypto maps
  if (!cryptoMapEntry.getDynamic()) {
    if (cryptoMapEntry.getAccessList() == null || cryptoMapEntry.getPeer() == null) {
      return;
    }
  } else {
    if (cryptoMapEntry.getAccessList() == null) {
      return;
    }
  }

  IpsecPhase2Policy ipsecPhase2Policy = toIpsecPhase2Policy(cryptoMapEntry);
  String ipsecPhase2PolicyName =
      String.format("~IPSEC_PHASE2_POLICY:%s~", cryptoMapNameSeqNumber);

  // add IPSec phase 2 policies to existing ones
  ImmutableSortedMap.Builder<String, IpsecPhase2Policy> ipsecPhase2PolicyBuilder =
      ImmutableSortedMap.naturalOrder();
  c.setIpsecPhase2Policies(
      ipsecPhase2PolicyBuilder
          .putAll(c.getIpsecPhase2Policies())
          .put(ipsecPhase2PolicyName, ipsecPhase2Policy)
          .build());

  ImmutableSortedMap.Builder<String, IpsecPeerConfig> ipsecPeerConfigsBuilder =
      ImmutableSortedMap.naturalOrder();
  c.setIpsecPeerConfigs(
      ipsecPeerConfigsBuilder
          .putAll(c.getIpsecPeerConfigs())
          .putAll(
              toIpsecPeerConfigs(
                  c,
                  cryptoMapEntry,
                  cryptoMapNameSeqNumber,
                  cryptoMapName,
                  ipsecPhase2PolicyName,
                  w))
          .build());
}
 
Example 18
Source File: NinjaBuild.java    From bazel with Apache License 2.0 4 votes vote down vote up
@Override
public ConfiguredTarget create(RuleContext ruleContext)
    throws InterruptedException, RuleErrorException, ActionConflictException {
  Map<String, List<String>> outputGroupsMap =
      ruleContext.attributes().get("output_groups", Type.STRING_LIST_DICT);
  NinjaGraphProvider graphProvider =
      ruleContext.getPrerequisite("ninja_graph", TransitionMode.TARGET, NinjaGraphProvider.class);
  Preconditions.checkNotNull(graphProvider);
  List<PathFragment> pathsToBuild =
      outputGroupsMap.values().stream()
          .flatMap(List::stream)
          .map(PathFragment::create)
          .collect(Collectors.toList());
  ImmutableSortedMap.Builder<PathFragment, Artifact> depsMapBuilder =
      ImmutableSortedMap.naturalOrder();
  ImmutableSortedMap.Builder<PathFragment, Artifact> symlinksMapBuilder =
      ImmutableSortedMap.naturalOrder();
  createDepsMap(
      ruleContext, graphProvider.getWorkingDirectory(), depsMapBuilder, symlinksMapBuilder);

  ImmutableSortedMap<PathFragment, Artifact> depsMap = depsMapBuilder.build();

  NinjaGraphArtifactsHelper artifactsHelper =
      new NinjaGraphArtifactsHelper(
          ruleContext,
          graphProvider.getOutputRoot(),
          graphProvider.getWorkingDirectory(),
          symlinksMapBuilder.build(),
          graphProvider.getOutputRootSymlinks());
  if (ruleContext.hasErrors()) {
    return null;
  }

  try {
    symlinkDepsMappings(ruleContext, artifactsHelper, depsMap);

    PhonyTargetArtifacts phonyTargetArtifacts =
        new PhonyTargetArtifacts(graphProvider.getPhonyTargetsMap(), artifactsHelper);
    ImmutableSet<PathFragment> symlinks =
        ImmutableSet.<PathFragment>builder()
            .addAll(graphProvider.getOutputRootInputsSymlinks())
            .addAll(depsMap.keySet())
            .build();

    new NinjaActionsHelper(
            ruleContext,
            artifactsHelper,
            graphProvider.getTargetsMap(),
            graphProvider.getPhonyTargetsMap(),
            phonyTargetArtifacts,
            pathsToBuild,
            symlinks)
        .createNinjaActions();

    if (!checkOrphanArtifacts(ruleContext)) {
      return null;
    }

    NestedSetBuilder<Artifact> filesToBuild = NestedSetBuilder.stableOrder();
    TreeMap<String, NestedSet<Artifact>> groups = Maps.newTreeMap();
    for (Map.Entry<String, List<String>> entry : outputGroupsMap.entrySet()) {
      NestedSet<Artifact> artifacts =
          getGroupArtifacts(
              ruleContext,
              entry.getValue(),
              graphProvider.getPhonyTargetsMap(),
              phonyTargetArtifacts,
              artifactsHelper);
      groups.put(entry.getKey(), artifacts);
      filesToBuild.addTransitive(artifacts);
    }

    if (ruleContext.hasErrors()) {
      return null;
    }

    return new RuleConfiguredTargetBuilder(ruleContext)
        .addProvider(RunfilesProvider.class, RunfilesProvider.EMPTY)
        .setFilesToBuild(filesToBuild.build())
        .addOutputGroups(groups)
        .build();
  } catch (GenericParsingException e) {
    ruleContext.ruleError(e.getMessage());
    return null;
  }
}
 
Example 19
Source File: Conversions.java    From batfish with Apache License 2.0 4 votes vote down vote up
/**
 * Converts a {@link CryptoMapEntry} to an {@link IpsecPhase2Policy} and a list of {@link
 * IpsecPeerConfig}
 */
private static void convertCryptoMapEntry(
    Configuration c,
    CryptoMapEntry cryptoMapEntry,
    String cryptoMapNameSeqNumber,
    String cryptoMapName,
    Warnings w) {
  // skipping incomplete static or dynamic crypto maps
  if (!cryptoMapEntry.getDynamic()) {
    if (cryptoMapEntry.getAccessList() == null || cryptoMapEntry.getPeer() == null) {
      return;
    }
  } else {
    if (cryptoMapEntry.getAccessList() == null) {
      return;
    }
  }

  IpsecPhase2Policy ipsecPhase2Policy = toIpsecPhase2Policy(cryptoMapEntry);
  String ipsecPhase2PolicyName =
      String.format("~IPSEC_PHASE2_POLICY:%s~", cryptoMapNameSeqNumber);

  // add IPSec phase 2 policies to existing ones
  ImmutableSortedMap.Builder<String, IpsecPhase2Policy> ipsecPhase2PolicyBuilder =
      ImmutableSortedMap.naturalOrder();
  c.setIpsecPhase2Policies(
      ipsecPhase2PolicyBuilder
          .putAll(c.getIpsecPhase2Policies())
          .put(ipsecPhase2PolicyName, ipsecPhase2Policy)
          .build());

  ImmutableSortedMap.Builder<String, IpsecPeerConfig> ipsecPeerConfigsBuilder =
      ImmutableSortedMap.naturalOrder();
  c.setIpsecPeerConfigs(
      ipsecPeerConfigsBuilder
          .putAll(c.getIpsecPeerConfigs())
          .putAll(
              toIpsecPeerConfigs(
                  c,
                  cryptoMapEntry,
                  cryptoMapNameSeqNumber,
                  cryptoMapName,
                  ipsecPhase2PolicyName,
                  w))
          .build());
}
 
Example 20
Source File: IpsecUtilHybridCloudTest.java    From batfish with Apache License 2.0 4 votes vote down vote up
@Before
public void setup() {
  // creates a topology with the following edges with edge between Tunnel9 and Tunnel10 having no
  // corresponding IPsec edges/nodes
  /*                                              AWS
  * +----------------+                      +----------------+
    |                |                      | Tunnel2        |
    |        Tunnel1 +----------------------+                |
    |    int 1 (shut)|                      |                |
    +----------------+                      +----------------+
  *
  *
  * */
  IpsecStaticPeerConfig ipsecPeerConfig1 =
      IpsecStaticPeerConfig.builder()
          .setSourceInterface("interface1")
          .setTunnelInterface("Tunnel1")
          .build();
  IpsecStaticPeerConfig ipsecPeerConfig2 =
      IpsecStaticPeerConfig.builder()
          .setSourceInterface("interface2")
          .setTunnelInterface("Tunnel2")
          .build();

  IpsecSession establishedSession =
      IpsecSession.builder().setNegotiatedIpsecP2Proposal(new IpsecPhase2Proposal()).build();

  MutableValueGraph<IpsecPeerConfigId, IpsecSession> graph =
      ValueGraphBuilder.directed().allowsSelfLoops(false).build();

  // populate IPsec topology
  graph.putEdgeValue(
      new IpsecPeerConfigId("peer1", "host1"),
      new IpsecPeerConfigId("peer2", "host2"),
      establishedSession);
  graph.putEdgeValue(
      new IpsecPeerConfigId("peer2", "host2"),
      new IpsecPeerConfigId("peer1", "host1"),
      establishedSession);

  _ipsecTopology = new IpsecTopology(graph);

  // populate Configurations to get IPsecPeerConfig objects from IPsecPeerConfigIds
  Configuration c1 = new Configuration("host1", CISCO_IOS);
  Configuration c2 = new Configuration("host2", AWS);
  c1.setIpsecPeerConfigs(ImmutableSortedMap.of("peer1", ipsecPeerConfig1));
  c2.setIpsecPeerConfigs(ImmutableSortedMap.of("peer2", ipsecPeerConfig2));

  ImmutableSortedMap.Builder<String, Interface> interfaceBuilder =
      ImmutableSortedMap.naturalOrder();
  c1.setInterfaces(
      interfaceBuilder
          .put("Tunnel1", Interface.builder().setName("Tunnel1").setOwner(c1).build())
          .put(
              "interface1",
              Interface.builder().setName("interface1").setOwner(c1).setActive(false).build())
          .build());
  interfaceBuilder = ImmutableSortedMap.naturalOrder();
  c2.setInterfaces(
      interfaceBuilder
          .put("Tunnel2", Interface.builder().setName("Tunnel2").setOwner(c2).build())
          .build());

  _configurations.put("host1", c1);
  _configurations.put("host2", c2);
}