private DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> buildContBuilderMod1(
      final String uri,
      final String rev,
      final String cont,
      final String contB,
      final String lf1,
      final String lf1_value) {
    final QName contQname = QName.create(uri, rev, cont);
    final QName contBQname = QName.create(uri, rev, contB);
    final QName lf1Qname = QName.create(contQname, lf1);

    final DataSchemaNode contSchemaNode = schemaContext.getDataChildByName(contQname);
    final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> dataContainerNodeAttrBuilder =
        Builders.containerBuilder((ContainerSchemaNode) contSchemaNode);

    Preconditions.checkState(contSchemaNode instanceof ContainerSchemaNode);
    final List<DataSchemaNode> instanceLf1_m1 =
        ControllerContext.findInstanceDataChildrenByName(
            (DataNodeContainer) contSchemaNode, lf1Qname.getLocalName());
    final DataSchemaNode schemaLf1_m1 = Iterables.getFirst(instanceLf1_m1, null);

    dataContainerNodeAttrBuilder.withChild(
        Builders.leafBuilder((LeafSchemaNode) schemaLf1_m1).withValue(lf1_value).build());

    final DataSchemaNode contBSchemaNode =
        ((ContainerSchemaNode) contSchemaNode).getDataChildByName(contBQname);

    final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> dataContainerB =
        Builders.containerBuilder((ContainerSchemaNode) contBSchemaNode);

    return dataContainerNodeAttrBuilder.withChild(dataContainerB.build());
  }
  private NormalizedNodeContext prepareNormalizedNodeContext() {
    final String rev = "2014-01-17";

    final DataSchemaNode schemaContNode = schemaContext;

    assertTrue(schemaContNode instanceof ContainerSchemaNode);

    final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> dataContSchemaContNode =
        Builders.containerBuilder((ContainerSchemaNode) schemaContNode);

    final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> modul1 =
        buildContBuilderMod1("module:one", rev, "cont_m1", "contB_m1", "lf1_m1", "lf1 m1 value");
    dataContSchemaContNode.withChild(modul1.build());

    final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> modul2 =
        buildContBuilderMod1("module:two", rev, "cont_m2", "contB_m2", "lf1_m2", "lf1 m2 value");
    dataContSchemaContNode.withChild(modul2.build());

    final NormalizedNodeContext testNormalizedNodeContext =
        new NormalizedNodeContext(
            new InstanceIdentifierContext<DataSchemaNode>(
                null, schemaContNode, null, schemaContext),
            dataContSchemaContNode.build());

    return testNormalizedNodeContext;
  }
public class DOMDataTreeListenerTest {

  private SchemaContext schemaContext;
  private AbstractDOMDataBroker domBroker;
  private ListeningExecutorService executor;
  private ExecutorService futureExecutor;
  private CommitExecutorService commitExecutor;

  private static final DataContainerChild<?, ?> OUTER_LIST =
      ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME)
          .withChild(ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1))
          .build();

  private static final DataContainerChild<?, ?> OUTER_LIST_2 =
      ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME)
          .withChild(ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 2))
          .build();

  private static final NormalizedNode<?, ?> TEST_CONTAINER =
      Builders.containerBuilder()
          .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(TestModel.TEST_QNAME))
          .withChild(OUTER_LIST)
          .build();

  private static final NormalizedNode<?, ?> TEST_CONTAINER_2 =
      Builders.containerBuilder()
          .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(TestModel.TEST_QNAME))
          .withChild(OUTER_LIST_2)
          .build();

  private static DOMDataTreeIdentifier ROOT_DATA_TREE_ID =
      new DOMDataTreeIdentifier(LogicalDatastoreType.CONFIGURATION, TestModel.TEST_PATH);

  private static DOMDataTreeIdentifier OUTER_LIST_DATA_TREE_ID =
      new DOMDataTreeIdentifier(LogicalDatastoreType.CONFIGURATION, TestModel.OUTER_LIST_PATH);

  @Before
  public void setupStore() {
    InMemoryDOMDataStore operStore =
        new InMemoryDOMDataStore("OPER", MoreExecutors.newDirectExecutorService());
    InMemoryDOMDataStore configStore =
        new InMemoryDOMDataStore("CFG", MoreExecutors.newDirectExecutorService());
    schemaContext = TestModel.createTestContext();

    operStore.onGlobalContextUpdated(schemaContext);
    configStore.onGlobalContextUpdated(schemaContext);

    ImmutableMap<LogicalDatastoreType, DOMStore> stores =
        ImmutableMap.<LogicalDatastoreType, DOMStore>builder() //
            .put(CONFIGURATION, configStore) //
            .put(OPERATIONAL, operStore) //
            .build();

    commitExecutor = new CommitExecutorService(Executors.newSingleThreadExecutor());
    futureExecutor = SpecialExecutors.newBlockingBoundedCachedThreadPool(1, 5, "FCB");
    executor =
        new DeadlockDetectingListeningExecutorService(
            commitExecutor,
            TransactionCommitDeadlockException.DEADLOCK_EXCEPTION_SUPPLIER,
            futureExecutor);
    domBroker = new SerializedDOMDataBroker(stores, executor);
  }

  @After
  public void tearDown() {
    if (executor != null) {
      executor.shutdownNow();
    }

    if (futureExecutor != null) {
      futureExecutor.shutdownNow();
    }
  }

  @Test
  public void writeContainerEmptyTreeTest() throws InterruptedException {
    CountDownLatch latch = new CountDownLatch(1);

    DOMDataTreeChangeService dataTreeChangeService = getDOMDataTreeChangeService();
    assertNotNull(
        "DOMDataTreeChangeService not found, cannot continue with test!", dataTreeChangeService);

    final TestDataTreeListener listener = new TestDataTreeListener(latch);
    final ListenerRegistration<TestDataTreeListener> listenerReg =
        dataTreeChangeService.registerDataTreeChangeListener(ROOT_DATA_TREE_ID, listener);

    final DOMDataTreeWriteTransaction writeTx = domBroker.newWriteOnlyTransaction();
    writeTx.put(LogicalDatastoreType.CONFIGURATION, TestModel.TEST_PATH, TEST_CONTAINER);
    writeTx.submit();

    latch.await(5, TimeUnit.SECONDS);

    assertEquals(1, listener.getReceivedChanges().size());
    final Collection<DataTreeCandidate> changes = listener.getReceivedChanges().get(0);
    assertEquals(1, changes.size());

    DataTreeCandidate candidate = changes.iterator().next();
    assertNotNull(candidate);
    DataTreeCandidateNode candidateRoot = candidate.getRootNode();
    checkChange(null, TEST_CONTAINER, ModificationType.WRITE, candidateRoot);
    listenerReg.close();
  }

  @Test
  public void replaceContainerContainerInTreeTest()
      throws InterruptedException, TransactionCommitFailedException {
    CountDownLatch latch = new CountDownLatch(2);

    DOMDataTreeChangeService dataTreeChangeService = getDOMDataTreeChangeService();
    assertNotNull(
        "DOMDataTreeChangeService not found, cannot continue with test!", dataTreeChangeService);

    DOMDataTreeWriteTransaction writeTx = domBroker.newWriteOnlyTransaction();
    writeTx.put(LogicalDatastoreType.CONFIGURATION, TestModel.TEST_PATH, TEST_CONTAINER);
    writeTx.submit().checkedGet();

    final TestDataTreeListener listener = new TestDataTreeListener(latch);
    final ListenerRegistration<TestDataTreeListener> listenerReg =
        dataTreeChangeService.registerDataTreeChangeListener(ROOT_DATA_TREE_ID, listener);
    writeTx = domBroker.newWriteOnlyTransaction();
    writeTx.put(LogicalDatastoreType.CONFIGURATION, TestModel.TEST_PATH, TEST_CONTAINER_2);
    writeTx.submit();

    latch.await(5, TimeUnit.SECONDS);

    assertEquals(2, listener.getReceivedChanges().size());
    Collection<DataTreeCandidate> changes = listener.getReceivedChanges().get(0);
    assertEquals(1, changes.size());

    DataTreeCandidate candidate = changes.iterator().next();
    assertNotNull(candidate);
    DataTreeCandidateNode candidateRoot = candidate.getRootNode();
    checkChange(null, TEST_CONTAINER, ModificationType.WRITE, candidateRoot);

    changes = listener.getReceivedChanges().get(1);
    assertEquals(1, changes.size());

    candidate = changes.iterator().next();
    assertNotNull(candidate);
    candidateRoot = candidate.getRootNode();
    checkChange(TEST_CONTAINER, TEST_CONTAINER_2, ModificationType.WRITE, candidateRoot);
    listenerReg.close();
  }

  @Test
  public void deleteContainerContainerInTreeTest()
      throws InterruptedException, TransactionCommitFailedException {
    CountDownLatch latch = new CountDownLatch(2);

    DOMDataTreeChangeService dataTreeChangeService = getDOMDataTreeChangeService();
    assertNotNull(
        "DOMDataTreeChangeService not found, cannot continue with test!", dataTreeChangeService);

    DOMDataTreeWriteTransaction writeTx = domBroker.newWriteOnlyTransaction();
    writeTx.put(LogicalDatastoreType.CONFIGURATION, TestModel.TEST_PATH, TEST_CONTAINER);
    writeTx.submit().checkedGet();

    final TestDataTreeListener listener = new TestDataTreeListener(latch);
    final ListenerRegistration<TestDataTreeListener> listenerReg =
        dataTreeChangeService.registerDataTreeChangeListener(ROOT_DATA_TREE_ID, listener);

    writeTx = domBroker.newWriteOnlyTransaction();
    writeTx.delete(LogicalDatastoreType.CONFIGURATION, TestModel.TEST_PATH);
    writeTx.submit();

    latch.await(5, TimeUnit.SECONDS);

    assertEquals(2, listener.getReceivedChanges().size());
    Collection<DataTreeCandidate> changes = listener.getReceivedChanges().get(0);
    assertEquals(1, changes.size());

    DataTreeCandidate candidate = changes.iterator().next();
    assertNotNull(candidate);
    DataTreeCandidateNode candidateRoot = candidate.getRootNode();
    checkChange(null, TEST_CONTAINER, ModificationType.WRITE, candidateRoot);

    changes = listener.getReceivedChanges().get(1);
    assertEquals(1, changes.size());

    candidate = changes.iterator().next();
    assertNotNull(candidate);
    candidateRoot = candidate.getRootNode();
    checkChange(TEST_CONTAINER, null, ModificationType.DELETE, candidateRoot);
    listenerReg.close();
  }

  @Test
  public void replaceChildListContainerInTreeTest()
      throws InterruptedException, TransactionCommitFailedException {
    CountDownLatch latch = new CountDownLatch(2);

    DOMDataTreeChangeService dataTreeChangeService = getDOMDataTreeChangeService();
    assertNotNull(
        "DOMDataTreeChangeService not found, cannot continue with test!", dataTreeChangeService);

    DOMDataTreeWriteTransaction writeTx = domBroker.newWriteOnlyTransaction();
    writeTx.put(LogicalDatastoreType.CONFIGURATION, TestModel.TEST_PATH, TEST_CONTAINER);
    writeTx.submit().checkedGet();

    final TestDataTreeListener listener = new TestDataTreeListener(latch);
    final ListenerRegistration<TestDataTreeListener> listenerReg =
        dataTreeChangeService.registerDataTreeChangeListener(ROOT_DATA_TREE_ID, listener);

    writeTx = domBroker.newWriteOnlyTransaction();
    writeTx.put(LogicalDatastoreType.CONFIGURATION, TestModel.OUTER_LIST_PATH, OUTER_LIST_2);
    writeTx.submit();

    latch.await(5, TimeUnit.SECONDS);

    assertEquals(2, listener.getReceivedChanges().size());
    Collection<DataTreeCandidate> changes = listener.getReceivedChanges().get(0);
    assertEquals(1, changes.size());

    DataTreeCandidate candidate = changes.iterator().next();
    assertNotNull(candidate);
    DataTreeCandidateNode candidateRoot = candidate.getRootNode();
    checkChange(null, TEST_CONTAINER, ModificationType.WRITE, candidateRoot);

    changes = listener.getReceivedChanges().get(1);
    assertEquals(1, changes.size());

    candidate = changes.iterator().next();
    assertNotNull(candidate);
    candidateRoot = candidate.getRootNode();
    checkChange(TEST_CONTAINER, TEST_CONTAINER_2, ModificationType.SUBTREE_MODIFIED, candidateRoot);
    final DataTreeCandidateNode modifiedChild =
        candidateRoot.getModifiedChild(
            new YangInstanceIdentifier.NodeIdentifier(TestModel.OUTER_LIST_QNAME));
    assertNotNull(modifiedChild);
    checkChange(OUTER_LIST, OUTER_LIST_2, ModificationType.WRITE, modifiedChild);
    listenerReg.close();
  }

  @Test
  public void rootModificationChildListenerTest()
      throws InterruptedException, TransactionCommitFailedException {
    CountDownLatch latch = new CountDownLatch(2);

    DOMDataTreeChangeService dataTreeChangeService = getDOMDataTreeChangeService();
    assertNotNull(
        "DOMDataTreeChangeService not found, cannot continue with test!", dataTreeChangeService);

    DOMDataTreeWriteTransaction writeTx = domBroker.newWriteOnlyTransaction();
    writeTx.put(LogicalDatastoreType.CONFIGURATION, TestModel.TEST_PATH, TEST_CONTAINER);
    writeTx.submit().checkedGet();

    final TestDataTreeListener listener = new TestDataTreeListener(latch);
    final ListenerRegistration<TestDataTreeListener> listenerReg =
        dataTreeChangeService.registerDataTreeChangeListener(OUTER_LIST_DATA_TREE_ID, listener);

    writeTx = domBroker.newWriteOnlyTransaction();
    writeTx.put(LogicalDatastoreType.CONFIGURATION, TestModel.TEST_PATH, TEST_CONTAINER_2);
    writeTx.submit().checkedGet();

    latch.await(1, TimeUnit.SECONDS);

    assertEquals(2, listener.getReceivedChanges().size());
    Collection<DataTreeCandidate> changes = listener.getReceivedChanges().get(0);
    assertEquals(1, changes.size());

    DataTreeCandidate candidate = changes.iterator().next();
    assertNotNull(candidate);
    DataTreeCandidateNode candidateRoot = candidate.getRootNode();
    checkChange(null, OUTER_LIST, ModificationType.WRITE, candidateRoot);

    changes = listener.getReceivedChanges().get(1);
    assertEquals(1, changes.size());

    candidate = changes.iterator().next();
    assertNotNull(candidate);
    candidateRoot = candidate.getRootNode();
    checkChange(OUTER_LIST, OUTER_LIST_2, ModificationType.WRITE, candidateRoot);
    listenerReg.close();
  }

  @Test
  public void listEntryChangeNonRootRegistrationTest()
      throws InterruptedException, TransactionCommitFailedException {
    CountDownLatch latch = new CountDownLatch(2);

    DOMDataTreeChangeService dataTreeChangeService = getDOMDataTreeChangeService();
    assertNotNull(
        "DOMDataTreeChangeService not found, cannot continue with test!", dataTreeChangeService);

    DOMDataTreeWriteTransaction writeTx = domBroker.newWriteOnlyTransaction();
    writeTx.put(LogicalDatastoreType.CONFIGURATION, TestModel.TEST_PATH, TEST_CONTAINER);
    writeTx.submit().checkedGet();

    final TestDataTreeListener listener = new TestDataTreeListener(latch);
    final ListenerRegistration<TestDataTreeListener> listenerReg =
        dataTreeChangeService.registerDataTreeChangeListener(OUTER_LIST_DATA_TREE_ID, listener);

    final YangInstanceIdentifier.NodeIdentifierWithPredicates outerListEntryId1 =
        new YangInstanceIdentifier.NodeIdentifierWithPredicates(
            TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1);
    final YangInstanceIdentifier.NodeIdentifierWithPredicates outerListEntryId2 =
        new YangInstanceIdentifier.NodeIdentifierWithPredicates(
            TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 2);
    final YangInstanceIdentifier.NodeIdentifierWithPredicates outerListEntryId3 =
        new YangInstanceIdentifier.NodeIdentifierWithPredicates(
            TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 3);

    final MapEntryNode outerListEntry1 =
        ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1);
    final MapEntryNode outerListEntry2 =
        ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 2);
    final MapEntryNode outerListEntry3 =
        ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 3);

    final MapNode listAfter =
        ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME)
            .withChild(outerListEntry2)
            .withChild(outerListEntry3)
            .build();

    writeTx = domBroker.newWriteOnlyTransaction();
    writeTx.delete(
        LogicalDatastoreType.CONFIGURATION, TestModel.OUTER_LIST_PATH.node(outerListEntryId1));
    writeTx.put(
        LogicalDatastoreType.CONFIGURATION,
        TestModel.OUTER_LIST_PATH.node(outerListEntryId2),
        outerListEntry2);
    writeTx.put(
        LogicalDatastoreType.CONFIGURATION,
        TestModel.OUTER_LIST_PATH.node(outerListEntryId3),
        outerListEntry3);
    writeTx.submit();

    latch.await(5, TimeUnit.SECONDS);

    assertEquals(2, listener.getReceivedChanges().size());
    Collection<DataTreeCandidate> changes = listener.getReceivedChanges().get(0);
    assertEquals(1, changes.size());

    DataTreeCandidate candidate = changes.iterator().next();
    assertNotNull(candidate);
    DataTreeCandidateNode candidateRoot = candidate.getRootNode();
    checkChange(null, OUTER_LIST, ModificationType.WRITE, candidateRoot);

    changes = listener.getReceivedChanges().get(1);
    assertEquals(1, changes.size());

    candidate = changes.iterator().next();
    assertNotNull(candidate);
    candidateRoot = candidate.getRootNode();
    checkChange(OUTER_LIST, listAfter, ModificationType.SUBTREE_MODIFIED, candidateRoot);
    final DataTreeCandidateNode entry1Canditate = candidateRoot.getModifiedChild(outerListEntryId1);
    checkChange(outerListEntry1, null, ModificationType.DELETE, entry1Canditate);
    final DataTreeCandidateNode entry2Canditate = candidateRoot.getModifiedChild(outerListEntryId2);
    checkChange(null, outerListEntry2, ModificationType.WRITE, entry2Canditate);
    final DataTreeCandidateNode entry3Canditate = candidateRoot.getModifiedChild(outerListEntryId3);
    checkChange(null, outerListEntry3, ModificationType.WRITE, entry3Canditate);
    listenerReg.close();
  }

  private static void checkChange(
      final NormalizedNode<?, ?> expectedBefore,
      final NormalizedNode<?, ?> expectedAfter,
      final ModificationType expectedMod,
      final DataTreeCandidateNode candidateNode) {
    if (expectedBefore != null) {
      assertTrue(candidateNode.getDataBefore().isPresent());
      assertEquals(expectedBefore, candidateNode.getDataBefore().get());
    } else {
      assertFalse(candidateNode.getDataBefore().isPresent());
    }

    if (expectedAfter != null) {
      assertTrue(candidateNode.getDataAfter().isPresent());
      assertEquals(expectedAfter, candidateNode.getDataAfter().get());
    } else {
      assertFalse(candidateNode.getDataAfter().isPresent());
    }

    assertEquals(expectedMod, candidateNode.getModificationType());
  }

  private DOMDataTreeChangeService getDOMDataTreeChangeService() {
    final DOMDataBrokerExtension extension =
        domBroker.getSupportedExtensions().get(DOMDataTreeChangeService.class);
    if (extension == null) {
      return null;
    }
    DOMDataTreeChangeService dataTreeChangeService = null;
    if (extension instanceof DOMDataTreeChangeService) {
      dataTreeChangeService = (DOMDataTreeChangeService) extension;
    }
    return dataTreeChangeService;
  }

  static class CommitExecutorService extends ForwardingExecutorService {

    ExecutorService delegate;

    public CommitExecutorService(final ExecutorService delegate) {
      this.delegate = delegate;
    }

    @Override
    protected ExecutorService delegate() {
      return delegate;
    }
  }

  static class TestDataTreeListener implements DOMDataTreeChangeListener {

    private final List<Collection<DataTreeCandidate>> receivedChanges = new ArrayList<>();
    private final CountDownLatch latch;

    public TestDataTreeListener(final CountDownLatch latch) {
      this.latch = latch;
    }

    @Override
    public void onDataTreeChanged(@Nonnull final Collection<DataTreeCandidate> changes) {
      receivedChanges.add(changes);
      latch.countDown();
    }

    public List<Collection<DataTreeCandidate>> getReceivedChanges() {
      return receivedChanges;
    }
  }
}
  @Override
  public synchronized DOMRpcResult toRpcResult(final NetconfMessage message, final SchemaPath rpc) {
    final NormalizedNode<?, ?> normalizedNode;
    final QName rpcQName = rpc.getLastComponent();
    if (NetconfMessageTransformUtil.isDataRetrievalOperation(rpcQName)) {
      final Element xmlData = NetconfMessageTransformUtil.getDataSubtree(message.getDocument());
      final ContainerSchemaNode schemaForDataRead =
          NetconfMessageTransformUtil.createSchemaForDataRead(schemaContext);
      final ContainerNode dataNode;

      try {
        dataNode =
            parserFactory
                .getContainerNodeParser()
                .parse(Collections.singleton(xmlData), schemaForDataRead);
      } catch (IllegalArgumentException e) {
        throw new IllegalArgumentException(
            String.format("Failed to parse data response %s", xmlData), e);
      }

      normalizedNode =
          Builders.containerBuilder()
              .withNodeIdentifier(
                  new YangInstanceIdentifier.NodeIdentifier(
                      NetconfMessageTransformUtil.NETCONF_RPC_REPLY_QNAME))
              .withChild(dataNode)
              .build();
    } else {

      Map<QName, RpcDefinition> currentMappedRpcs = mappedRpcs;

      // Determine whether a base netconf operation is being invoked and also check if the device
      // exposed model for base netconf
      // If no, use pre built base netconf operations model
      final boolean needToUseBaseCtx = mappedRpcs.get(rpcQName) == null && isBaseRpc(rpcQName);
      if (needToUseBaseCtx) {
        currentMappedRpcs = MAPPED_BASE_RPCS;
      }

      final RpcDefinition rpcDefinition = currentMappedRpcs.get(rpcQName);
      Preconditions.checkArgument(
          rpcDefinition != null, "Unable to parse response of %s, the rpc is unknown", rpcQName);

      // In case no input for rpc is defined, we can simply construct the payload here
      if (rpcDefinition.getOutput() == null) {
        Preconditions.checkArgument(
            XmlElement.fromDomDocument(message.getDocument())
                .getOnlyChildElementWithSameNamespaceOptionally("ok")
                .isPresent(),
            "Unexpected content in response of rpc: %s, %s",
            rpcDefinition.getQName(),
            message);
        normalizedNode = null;
      } else {
        final Element element = message.getDocument().getDocumentElement();
        try {
          normalizedNode =
              parserFactory
                  .getContainerNodeParser()
                  .parse(Collections.singleton(element), rpcDefinition.getOutput());
        } catch (IllegalArgumentException e) {
          throw new IllegalArgumentException(
              String.format("Failed to parse RPC response %s", element), e);
        }
      }
    }
    return new DefaultDOMRpcResult(normalizedNode);
  }
 @Override
 protected final DataContainerNodeBuilder<InstanceIdentifier.NodeIdentifier, ContainerNode>
     getBuilder(ContainerSchemaNode schema) {
   return Builders.containerBuilder(schema);
 }
 protected static DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> top() {
   return Builders.containerBuilder().withNodeIdentifier(new NodeIdentifier(Top.QNAME));
 }
 protected static CollectionNodeBuilder<MapEntryNode, OrderedMapNode> nestedMap() {
   return Builders.orderedMapBuilder().withNodeIdentifier(new NodeIdentifier(NestedList.QNAME));
 }
  @Test
  public void testPrefixNlri() throws BGPParsingException {
    setUp(this.prefixNlri);

    // test BA form
    assertNull(this.dest.getDistinguisher());
    assertEquals(ProtocolId.IsisLevel2, this.dest.getProtocolId());
    assertEquals(BigInteger.ONE, this.dest.getIdentifier().getValue());

    final PrefixCase pCase = ((PrefixCase) this.dest.getObjectType());

    final AdvertisingNodeDescriptors local = pCase.getAdvertisingNodeDescriptors();
    assertEquals(new AsNumber(72L), local.getAsNumber());
    assertEquals(new DomainIdentifier(0x28282828L), local.getDomainId());
    assertEquals(
        new IsisNodeCaseBuilder()
            .setIsisNode(
                new IsisNodeBuilder()
                    .setIsoSystemId(
                        new IsoSystemIdentifier(
                            new byte[] {
                              (byte) 0x00,
                              (byte) 0x00,
                              (byte) 0x00,
                              (byte) 0x00,
                              (byte) 0x00,
                              (byte) 0x42
                            }))
                    .build())
            .build(),
        local.getCRouterIdentifier());

    final PrefixDescriptors pd = pCase.getPrefixDescriptors();
    assertEquals(OspfRouteType.External1, pd.getOspfRouteType());
    assertEquals(new TopologyIdentifier(15), pd.getMultiTopologyId());
    assertEquals(
        new Ipv4Prefix("255.255.0.0/16"), pd.getIpReachabilityInformation().getIpv4Prefix());

    final ByteBuf buffer = Unpooled.buffer();
    LinkstateNlriParser.serializeNlri(this.dest, buffer);
    assertArrayEquals(this.prefixNlri, ByteArray.readAllBytes(buffer));

    // test BI form
    final DataContainerNodeAttrBuilder<YangInstanceIdentifier.NodeIdentifier, UnkeyedListEntryNode>
        linkstateBI = ImmutableUnkeyedListEntryNodeBuilder.create();
    linkstateBI.withNodeIdentifier(C_LINKSTATE_NID);

    final ImmutableLeafNodeBuilder<String> protocolId = new ImmutableLeafNodeBuilder<>();
    protocolId.withNodeIdentifier(LinkstateNlriParser.PROTOCOL_ID_NID);
    protocolId.withValue("isis-level2");
    linkstateBI.addChild(protocolId.build());

    final ImmutableLeafNodeBuilder<BigInteger> identifier = new ImmutableLeafNodeBuilder<>();
    identifier.withNodeIdentifier(LinkstateNlriParser.IDENTIFIER_NID);
    identifier.withValue(BigInteger.ONE);
    linkstateBI.addChild(identifier.build());

    final DataContainerNodeBuilder<NodeIdentifier, ChoiceNode> objectType =
        Builders.choiceBuilder();
    objectType.withNodeIdentifier(LinkstateNlriParser.OBJECT_TYPE_NID);

    // advertising node descriptors
    final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> advertisingNodeDescriptors =
        Builders.containerBuilder();
    advertisingNodeDescriptors.withNodeIdentifier(
        LinkstateNlriParser.ADVERTISING_NODE_DESCRIPTORS_NID);

    final ImmutableLeafNodeBuilder<Long> asNumber = new ImmutableLeafNodeBuilder<>();
    asNumber.withNodeIdentifier(NodeNlriParser.AS_NUMBER_NID);
    asNumber.withValue(72L);
    advertisingNodeDescriptors.addChild(asNumber.build());

    final ImmutableLeafNodeBuilder<Long> domainID = new ImmutableLeafNodeBuilder<>();
    domainID.withNodeIdentifier(NodeNlriParser.DOMAIN_NID);
    domainID.withValue(673720360L);
    advertisingNodeDescriptors.addChild(domainID.build());

    final DataContainerNodeBuilder<NodeIdentifier, ChoiceNode> crouterId = Builders.choiceBuilder();
    crouterId.withNodeIdentifier(C_ROUTER_ID_NID);

    final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> isisNode =
        Builders.containerBuilder();
    isisNode.withNodeIdentifier(NodeNlriParser.ISIS_NODE_NID);

    final ImmutableLeafNodeBuilder<byte[]> isoSystemID = new ImmutableLeafNodeBuilder<>();
    isoSystemID.withNodeIdentifier(NodeNlriParser.ISO_SYSTEM_NID);
    isoSystemID.withValue(new byte[] {0, 0, 0, 0, 0, (byte) 0x42});

    isisNode.addChild(isoSystemID.build());
    crouterId.addChild(isisNode.build());
    advertisingNodeDescriptors.addChild(crouterId.build());

    // prefix descriptors
    final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> prefixDescriptors =
        Builders.containerBuilder();
    prefixDescriptors.withNodeIdentifier(LinkstateNlriParser.PREFIX_DESCRIPTORS_NID);
    prefixDescriptors.addChild(asNumber.build());
    prefixDescriptors.addChild(domainID.build());

    final ImmutableLeafNodeBuilder<Integer> multiTopologyId = new ImmutableLeafNodeBuilder<>();
    multiTopologyId.withNodeIdentifier(TlvUtil.MULTI_TOPOLOGY_NID);
    multiTopologyId.withValue(15);

    prefixDescriptors.addChild(multiTopologyId.build());

    final ImmutableLeafNodeBuilder<String> ipReachabilityInformation =
        new ImmutableLeafNodeBuilder<>();
    ipReachabilityInformation.withNodeIdentifier(PrefixNlriParser.IP_REACH_NID);
    ipReachabilityInformation.withValue("255.255.0.0/16");

    prefixDescriptors.addChild(ipReachabilityInformation.build());

    final ImmutableLeafNodeBuilder<String> ospfRouteType = new ImmutableLeafNodeBuilder<>();
    ospfRouteType.withNodeIdentifier(PrefixNlriParser.OSPF_ROUTE_NID);
    ospfRouteType.withValue("external1");

    prefixDescriptors.addChild(ospfRouteType.build());

    objectType.addChild(advertisingNodeDescriptors.build());
    objectType.addChild(prefixDescriptors.build());

    linkstateBI.addChild(objectType.build());
    assertEquals(this.dest, LinkstateNlriParser.extractLinkstateDestination(linkstateBI.build()));
  }
  @Test
  public void testLinkNlri() throws BGPParsingException {
    setUp(this.linkNlri);

    // test BA form
    assertNull(this.dest.getDistinguisher());
    assertEquals(ProtocolId.IsisLevel2, this.dest.getProtocolId());
    assertEquals(BigInteger.ONE, this.dest.getIdentifier().getValue());

    final LinkCase lCase = ((LinkCase) this.dest.getObjectType());

    final LocalNodeDescriptors local = lCase.getLocalNodeDescriptors();
    assertEquals(new AsNumber(72L), local.getAsNumber());
    assertEquals(new DomainIdentifier(0x28282828L), local.getDomainId());
    assertEquals(
        new IsisNodeCaseBuilder()
            .setIsisNode(
                new IsisNodeBuilder()
                    .setIsoSystemId(
                        new IsoSystemIdentifier(
                            new byte[] {
                              (byte) 0x00,
                              (byte) 0x00,
                              (byte) 0x00,
                              (byte) 0x00,
                              (byte) 0x00,
                              (byte) 0x42
                            }))
                    .build())
            .build(),
        local.getCRouterIdentifier());
    assertEquals("1.1.1.1", local.getBgpRouterId().getValue());
    assertEquals(new AsNumber(258L), local.getMemberAsn());

    final RemoteNodeDescriptors remote = lCase.getRemoteNodeDescriptors();
    assertEquals(new AsNumber(72L), remote.getAsNumber());
    assertEquals(new DomainIdentifier(0x28282828L), remote.getDomainId());
    assertEquals(
        new OspfNodeCaseBuilder()
            .setOspfNode(new OspfNodeBuilder().setOspfRouterId(0x00000040L).build())
            .build(),
        remote.getCRouterIdentifier());
    assertEquals(new AsNumber(259L), remote.getMemberAsn());
    assertEquals("1.1.1.2", remote.getBgpRouterId().getValue());

    final LinkDescriptors ld = lCase.getLinkDescriptors();
    assertEquals("197.20.160.42", ld.getIpv4InterfaceAddress().getValue());
    assertEquals("197.20.160.40", ld.getIpv4NeighborAddress().getValue());

    final ByteBuf buffer = Unpooled.buffer();
    LinkstateNlriParser.serializeNlri(this.dest, buffer);
    assertArrayEquals(this.linkNlri, ByteArray.readAllBytes(buffer));

    // test BI form
    final DataContainerNodeAttrBuilder<YangInstanceIdentifier.NodeIdentifier, UnkeyedListEntryNode>
        linkstateBI = ImmutableUnkeyedListEntryNodeBuilder.create();
    linkstateBI.withNodeIdentifier(C_LINKSTATE_NID);

    final ImmutableLeafNodeBuilder<String> protocolId = new ImmutableLeafNodeBuilder<>();
    protocolId.withNodeIdentifier(LinkstateNlriParser.PROTOCOL_ID_NID);
    protocolId.withValue("isis-level2");
    linkstateBI.addChild(protocolId.build());

    final ImmutableLeafNodeBuilder<BigInteger> identifier = new ImmutableLeafNodeBuilder<>();
    identifier.withNodeIdentifier(LinkstateNlriParser.IDENTIFIER_NID);
    identifier.withValue(BigInteger.ONE);
    linkstateBI.addChild(identifier.build());

    final DataContainerNodeBuilder<NodeIdentifier, ChoiceNode> objectType =
        Builders.choiceBuilder();
    objectType.withNodeIdentifier(LinkstateNlriParser.OBJECT_TYPE_NID);

    // local node descriptors
    final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> localNodeDescriptors =
        Builders.containerBuilder();
    localNodeDescriptors.withNodeIdentifier(LinkstateNlriParser.LOCAL_NODE_DESCRIPTORS_NID);

    final ImmutableLeafNodeBuilder<Long> asNumber = new ImmutableLeafNodeBuilder<>();
    asNumber.withNodeIdentifier(NodeNlriParser.AS_NUMBER_NID);
    asNumber.withValue(72L);
    localNodeDescriptors.addChild(asNumber.build());

    final ImmutableLeafNodeBuilder<Long> domainID = new ImmutableLeafNodeBuilder<>();
    domainID.withNodeIdentifier(NodeNlriParser.DOMAIN_NID);
    domainID.withValue(0x28282828L);
    localNodeDescriptors.addChild(domainID.build());

    final DataContainerNodeBuilder<NodeIdentifier, ChoiceNode> crouterId = Builders.choiceBuilder();
    crouterId.withNodeIdentifier(C_ROUTER_ID_NID);

    final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> isisNode =
        Builders.containerBuilder();
    isisNode.withNodeIdentifier(NodeNlriParser.ISIS_NODE_NID);

    final ImmutableLeafNodeBuilder<byte[]> isoSystemID = new ImmutableLeafNodeBuilder<>();
    isoSystemID.withNodeIdentifier(NodeNlriParser.ISO_SYSTEM_NID);
    isoSystemID.withValue(new byte[] {0, 0, 0, 0, 0, (byte) 0x42});

    isisNode.addChild(isoSystemID.build());
    crouterId.addChild(isisNode.build());
    localNodeDescriptors.addChild(crouterId.build());

    final ImmutableLeafNodeBuilder<String> bgpRouterId = new ImmutableLeafNodeBuilder<>();
    bgpRouterId.withNodeIdentifier(NodeNlriParser.BGP_ROUTER_NID);
    bgpRouterId.withValue("1.1.1.1");

    final ImmutableLeafNodeBuilder<Long> memberAsn = new ImmutableLeafNodeBuilder<>();
    memberAsn.withNodeIdentifier(NodeNlriParser.MEMBER_ASN_NID);
    memberAsn.withValue(258L);

    localNodeDescriptors.addChild(bgpRouterId.build());
    localNodeDescriptors.addChild(memberAsn.build());

    // remote descriptors
    final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> remoteNodeDescriptors =
        Builders.containerBuilder();
    remoteNodeDescriptors.withNodeIdentifier(LinkstateNlriParser.REMOTE_NODE_DESCRIPTORS_NID);
    remoteNodeDescriptors.addChild(asNumber.build());
    remoteNodeDescriptors.addChild(domainID.build());

    final DataContainerNodeBuilder<NodeIdentifier, ChoiceNode> crouterId2 =
        Builders.choiceBuilder();
    crouterId2.withNodeIdentifier(C_ROUTER_ID_NID);

    final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> ospfNode =
        Builders.containerBuilder();
    ospfNode.withNodeIdentifier(NodeNlriParser.OSPF_NODE_NID);

    final ImmutableLeafNodeBuilder<Long> ospfRouterId = new ImmutableLeafNodeBuilder<>();
    ospfRouterId.withNodeIdentifier(NodeNlriParser.OSPF_ROUTER_NID);
    ospfRouterId.withValue(0x00000040L);
    ospfNode.addChild(ospfRouterId.build());
    crouterId2.addChild(ospfNode.build());
    remoteNodeDescriptors.addChild(crouterId2.build());
    final ImmutableLeafNodeBuilder<String> bgpRouterIdRemote = new ImmutableLeafNodeBuilder<>();
    bgpRouterIdRemote.withNodeIdentifier(NodeNlriParser.BGP_ROUTER_NID);
    bgpRouterIdRemote.withValue("1.1.1.2");
    remoteNodeDescriptors.addChild(bgpRouterIdRemote.build());

    final ImmutableLeafNodeBuilder<Long> memberAsnRemote = new ImmutableLeafNodeBuilder<>();
    memberAsnRemote.withNodeIdentifier(NodeNlriParser.MEMBER_ASN_NID);
    memberAsnRemote.withValue(259L);
    remoteNodeDescriptors.addChild(memberAsnRemote.build());

    // link descritpors
    final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> linkDescriptors =
        Builders.containerBuilder();
    linkDescriptors.withNodeIdentifier(LinkstateNlriParser.LINK_DESCRIPTORS_NID);

    final ImmutableLeafNodeBuilder<Long> linkLocalIdentifier = new ImmutableLeafNodeBuilder<>();
    linkLocalIdentifier.withNodeIdentifier(LinkNlriParser.LINK_LOCAL_NID);
    linkLocalIdentifier.withValue(16909060L);

    final ImmutableLeafNodeBuilder<Long> linkRemoteIdentifier = new ImmutableLeafNodeBuilder<>();
    linkRemoteIdentifier.withNodeIdentifier(LinkNlriParser.LINK_REMOTE_NID);
    linkRemoteIdentifier.withValue(168496141L);

    final ImmutableLeafNodeBuilder<String> ipv4InterfaceAddress = new ImmutableLeafNodeBuilder<>();
    ipv4InterfaceAddress.withNodeIdentifier(LinkNlriParser.IPV4_IFACE_NID);
    ipv4InterfaceAddress.withValue("197.20.160.42");

    final ImmutableLeafNodeBuilder<String> ipv4NeighborAddress = new ImmutableLeafNodeBuilder<>();
    ipv4NeighborAddress.withNodeIdentifier(LinkNlriParser.IPV4_NEIGHBOR_NID);
    ipv4NeighborAddress.withValue("197.20.160.40");

    final ImmutableLeafNodeBuilder<Integer> multiTopologyId = new ImmutableLeafNodeBuilder<>();
    multiTopologyId.withNodeIdentifier(TlvUtil.MULTI_TOPOLOGY_NID);
    multiTopologyId.withValue(3);

    linkDescriptors.addChild(linkLocalIdentifier.build());
    linkDescriptors.addChild(linkRemoteIdentifier.build());
    linkDescriptors.addChild(ipv4InterfaceAddress.build());
    linkDescriptors.addChild(ipv4NeighborAddress.build());
    linkDescriptors.addChild(multiTopologyId.build());

    objectType.addChild(localNodeDescriptors.build());
    objectType.addChild(remoteNodeDescriptors.build());
    objectType.addChild(linkDescriptors.build());

    linkstateBI.addChild(objectType.build());
    assertEquals(this.dest, LinkstateNlriParser.extractLinkstateDestination(linkstateBI.build()));
  }
  @Test
  public void testNodeNlri() throws BGPParsingException {
    setUp(this.nodeNlri);

    // test BA form
    assertNull(this.dest.getDistinguisher());
    assertEquals(ProtocolId.IsisLevel2, this.dest.getProtocolId());
    assertEquals(BigInteger.ONE, this.dest.getIdentifier().getValue());
    final NodeCase nCase = ((NodeCase) this.dest.getObjectType());

    final NodeDescriptors nodeD = nCase.getNodeDescriptors();
    assertEquals(new AsNumber(72L), nodeD.getAsNumber());
    assertEquals(new DomainIdentifier(0x28282828L), nodeD.getDomainId());
    assertEquals(
        new IsisPseudonodeCaseBuilder()
            .setIsisPseudonode(
                new IsisPseudonodeBuilder()
                    .setPsn((short) 5)
                    .setIsIsRouterIdentifier(
                        new IsIsRouterIdentifierBuilder()
                            .setIsoSystemId(
                                new IsoSystemIdentifier(new byte[] {0, 0, 0, 0, 0, (byte) 0x39}))
                            .build())
                    .build())
            .build(),
        nodeD.getCRouterIdentifier());

    final ByteBuf buffer = Unpooled.buffer();
    LinkstateNlriParser.serializeNlri(this.dest, buffer);
    assertArrayEquals(this.nodeNlri, ByteArray.readAllBytes(buffer));

    // test BI form
    final DataContainerNodeAttrBuilder<YangInstanceIdentifier.NodeIdentifier, UnkeyedListEntryNode>
        linkstateBI = ImmutableUnkeyedListEntryNodeBuilder.create();
    linkstateBI.withNodeIdentifier(C_LINKSTATE_NID);

    final ImmutableLeafNodeBuilder<String> protocolId = new ImmutableLeafNodeBuilder<>();
    protocolId.withNodeIdentifier(LinkstateNlriParser.PROTOCOL_ID_NID);
    protocolId.withValue("isis-level2");
    linkstateBI.addChild(protocolId.build());

    final ImmutableLeafNodeBuilder<BigInteger> identifier = new ImmutableLeafNodeBuilder<>();
    identifier.withNodeIdentifier(LinkstateNlriParser.IDENTIFIER_NID);
    identifier.withValue(BigInteger.ONE);
    linkstateBI.addChild(identifier.build());

    final DataContainerNodeBuilder<NodeIdentifier, ChoiceNode> objectType =
        Builders.choiceBuilder();
    objectType.withNodeIdentifier(LinkstateNlriParser.OBJECT_TYPE_NID);

    final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> nodeDescriptors =
        Builders.containerBuilder();
    nodeDescriptors.withNodeIdentifier(LinkstateNlriParser.NODE_DESCRIPTORS_NID);

    final ImmutableLeafNodeBuilder<Long> asNumber = new ImmutableLeafNodeBuilder<>();
    asNumber.withNodeIdentifier(NodeNlriParser.AS_NUMBER_NID);
    asNumber.withValue(72L);
    nodeDescriptors.addChild(asNumber.build());

    final ImmutableLeafNodeBuilder<Long> areaID = new ImmutableLeafNodeBuilder<>();
    areaID.withNodeIdentifier(NodeNlriParser.AREA_NID);
    areaID.withValue(2697513L);
    nodeDescriptors.addChild(areaID.build());

    final ImmutableLeafNodeBuilder<Long> domainID = new ImmutableLeafNodeBuilder<>();
    domainID.withNodeIdentifier(NodeNlriParser.DOMAIN_NID);
    domainID.withValue(0x28282828L);
    nodeDescriptors.addChild(domainID.build());

    final DataContainerNodeBuilder<NodeIdentifier, ChoiceNode> crouterId = Builders.choiceBuilder();
    crouterId.withNodeIdentifier(C_ROUTER_ID_NID);

    final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> isisNode =
        Builders.containerBuilder();
    isisNode.withNodeIdentifier(NodeNlriParser.ISIS_PSEUDONODE_NID);

    final ImmutableLeafNodeBuilder<byte[]> isoSystemID = new ImmutableLeafNodeBuilder<>();
    isoSystemID.withNodeIdentifier(NodeNlriParser.ISO_SYSTEM_NID);
    isoSystemID.withValue(new byte[] {0, 0, 0, 0, 0, (byte) 0x39});
    isisNode.addChild(isoSystemID.build());
    isisNode.addChild(
        Builders.leafBuilder()
            .withNodeIdentifier(NodeNlriParser.PSN_NID)
            .withValue((short) 5)
            .build());
    crouterId.addChild(isisNode.build());

    nodeDescriptors.addChild(crouterId.build());
    objectType.addChild(nodeDescriptors.build());
    linkstateBI.addChild(objectType.build());

    assertEquals(this.dest, LinkstateNlriParser.extractLinkstateDestination(linkstateBI.build()));
  }