org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier Java Examples

The following examples show how to use org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier. 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: Bug5968Test.java    From yangtools with Eclipse Public License 1.0 6 votes vote down vote up
private static DataTree initDataTree(final SchemaContext schemaContext, final boolean withMapNode)
        throws DataValidationFailedException {
    final DataTree inMemoryDataTree = new InMemoryDataTreeFactory().create(
            DataTreeConfiguration.DEFAULT_CONFIGURATION, schemaContext);

    final DataContainerNodeBuilder<NodeIdentifier, ContainerNode> root = Builders.containerBuilder()
            .withNodeIdentifier(new NodeIdentifier(ROOT));
    final DataTreeModification modificationTree = inMemoryDataTree.takeSnapshot().newModification();
    modificationTree.write(
            YangInstanceIdentifier.of(ROOT),
            withMapNode ? root.withChild(
                    Builders.mapBuilder().withNodeIdentifier(new NodeIdentifier(MY_LIST)).build()).build() : root
                    .build());
    modificationTree.ready();

    inMemoryDataTree.validate(modificationTree);
    final DataTreeCandidate prepare = inMemoryDataTree.prepare(modificationTree);
    inMemoryDataTree.commit(prepare);

    return inMemoryDataTree;
}
 
Example #2
Source File: InstanceIdToNodesTest.java    From yangtools with Eclipse Public License 1.0 6 votes vote down vote up
@Test
public void testInAugment() {
    final LeafNode<?> leaf = Builders.leafBuilder().withNodeIdentifier(augmentedLeaf).withValue("").build();
    final ContainerNode expectedFilter = Builders
            .containerBuilder()
            .withNodeIdentifier(rootContainer)
            .withChild(
                    Builders.containerBuilder()
                            .withNodeIdentifier(outerContainer)
                            .withChild(
                                    Builders.augmentationBuilder()
                                            .withNodeIdentifier(augmentation)
                                            .withChild(
                                                    leaf).build()).build()).build();

    final NormalizedNode<?, ?> filter = ImmutableNodes.fromInstanceId(ctx,
            YangInstanceIdentifier.create(rootContainer, outerContainer, augmentation, augmentedLeaf), leaf);
    assertEquals(expectedFilter, filter);
}
 
Example #3
Source File: Bug5830Test.java    From yangtools with Eclipse Public License 1.0 6 votes vote down vote up
private static void testMandatoryLeaf2IsPresent(final SchemaContext schemaContext,
        final boolean withPresenceContianer) throws DataValidationFailedException {
    final DataTree inMemoryDataTree = initDataTree(schemaContext);

    final MapEntryNode taskEntryNode = Builders.mapEntryBuilder()
            .withNodeIdentifier(NodeIdentifierWithPredicates.of(TASK, ImmutableMap.of(TASK_ID, "123")))
            .withChild(ImmutableNodes.leafNode(TASK_ID, "123"))
            .withChild(ImmutableNodes.leafNode(TASK_MANDATORY_LEAF, "mandatory data"))
            .withChild(createTaskDataMultipleContainer(withPresenceContianer)).build();

    final DataTreeModification modificationTree = inMemoryDataTree.takeSnapshot().newModification();
    modificationTree.write(
            YangInstanceIdentifier.of(TASK_CONTAINER).node(TASK)
                    .node(NodeIdentifierWithPredicates.of(TASK, ImmutableMap.of(TASK_ID, "123"))), taskEntryNode);
    modificationTree.ready();

    inMemoryDataTree.validate(modificationTree);
    final DataTreeCandidate prepare = inMemoryDataTree.prepare(modificationTree);
    inMemoryDataTree.commit(prepare);
}
 
Example #4
Source File: AbstractNodeContainerModificationStrategy.java    From yangtools with Eclipse Public License 1.0 6 votes vote down vote up
@Override
protected final void checkTouchApplicable(final ModificationPath path, final NodeModification modification,
        final Optional<? extends TreeNode> current, final Version version) throws DataValidationFailedException {
    final TreeNode currentNode;
    if (!current.isPresent()) {
        currentNode = defaultTreeNode();
        if (currentNode == null) {
            if (!modification.getOriginal().isPresent()) {
                final YangInstanceIdentifier id = path.toInstanceIdentifier();
                throw new ModifiedNodeDoesNotExistException(id,
                    String.format("Node %s does not exist. Cannot apply modification to its children.", id));
            }

            throw new ConflictingModificationAppliedException(path.toInstanceIdentifier(),
                "Node was deleted by other transaction.");
        }
    } else {
        currentNode = current.get();
    }

    checkChildPreconditions(path, modification, currentNode, version);
}
 
Example #5
Source File: TestUtils.java    From yangtools with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Returns a test document.
 *
 * <pre>
 * root
 *     leaf-c "waz"
 *     list-a
 *          leaf-a "foo"
 *     list-a
 *          leaf-a "bar"
 *          list-b
 *                  leaf-b "one"
 *          list-b
 *                  leaf-b "two"
 *     container-a
 *          container-b
 *                  leaf-d "three"
 * </pre>
 *
 * @return A test document instance.
 */
public static NormalizedNode<?, ?> createNormalizedNodes() {
    return ImmutableContainerNodeBuilder
            .create()
            .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(ROOT_QNAME))
            .withChild(ImmutableNodes.leafNode(LEAF_C_QNAME, WAZ))
            .withChild(mapNodeBuilder(LIST_A_QNAME)
                    .withChild(mapEntry(LIST_A_QNAME, LEAF_A_QNAME, FOO))
                    .withChild(mapEntryBuilder(LIST_A_QNAME, LEAF_A_QNAME, BAR)
                            .withChild(mapNodeBuilder(LIST_B_QNAME)
                                    .withChild(mapEntry(LIST_B_QNAME, LEAF_B_QNAME, ONE))
                                    .withChild(mapEntry(LIST_B_QNAME, LEAF_B_QNAME, TWO))
                                    .build())
                            .build())
                    .build())
            .withChild(ImmutableContainerNodeBuilder.create()
                    .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(CONTAINER_A_QNAME))
                    .withChild(ImmutableContainerNodeBuilder.create()
                        .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(CONTAINER_B_QNAME))
                            .withChild(ImmutableNodes.leafNode(LEAF_D_QNAME, THREE))
                            .build())
                    .build())
            .build();
}
 
Example #6
Source File: InMemoryDataTreeFactory.java    From yangtools with Eclipse Public License 1.0 6 votes vote down vote up
private static @NonNull NormalizedNode<?, ?> createRoot(final YangInstanceIdentifier path) {
    if (path.isEmpty()) {
        return ROOT_CONTAINER;
    }

    final PathArgument arg = path.getLastPathArgument();
    if (arg instanceof NodeIdentifier) {
        return ImmutableContainerNodeBuilder.create().withNodeIdentifier((NodeIdentifier) arg).build();
    }
    if (arg instanceof NodeIdentifierWithPredicates) {
        return ImmutableNodes.mapEntryBuilder().withNodeIdentifier((NodeIdentifierWithPredicates) arg).build();
    }

    // FIXME: implement augmentations and leaf-lists
    throw new IllegalArgumentException("Unsupported root node " + arg);
}
 
Example #7
Source File: EthSegRParserTest.java    From bgpcep with Eclipse Public License 1.0 6 votes vote down vote up
@Test
public void parser2Test() {
    final EsRouteCase expected = new EsRouteCaseBuilder().setEsRoute(new EsRouteBuilder()
            .setEsi(LAN_AUT_GEN_CASE).setOrigRouteIp(IPV6).build()).build();
    assertArrayEquals(RESULT2, ByteArray.getAllBytes(this.parser.serializeEvpn(expected,
            Unpooled.wrappedBuffer(ROUDE_DISTIN))));

    final EvpnChoice result = this.parser.parseEvpn(Unpooled.wrappedBuffer(VALUE2));
    assertEquals(expected, result);

    final DataContainerNodeBuilder<YangInstanceIdentifier.NodeIdentifier, ChoiceNode> choice = Builders
            .choiceBuilder();
    choice.withNodeIdentifier(EthSegRParser.ES_ROUTE_NID);
    final ContainerNode arbitraryC = createContBuilder(EthSegRParser.ES_ROUTE_NID)
            .addChild(LanParserTest.createLanChoice())
            .addChild(createValueBuilder(IPV6_MODEL, ORI_NID).build()).build();
    final EvpnChoice modelResult = this.parser.serializeEvpnModel(arbitraryC);
    assertEquals(expected, modelResult);

    final EvpnChoice keyResult = this.parser.createRouteKey(arbitraryC);
    assertEquals(expected, keyResult);
}
 
Example #8
Source File: EffectiveRibInWriter.java    From bgpcep with Eclipse Public License 1.0 6 votes vote down vote up
EffectiveRibInWriter(
        final BGPRouteEntryImportParameters peer,
        final RIB rib,
        final DOMTransactionChain chain,
        final YangInstanceIdentifier peerIId,
        final Set<TablesKey> tables,
        final BGPTableTypeRegistryConsumer tableTypeRegistry,
        final List<RouteTarget> rtMemberships,
        final ClientRouteTargetContrainCache rtCache) {
    this.registry = requireNonNull(rib.getRibSupportContext());
    this.chain = requireNonNull(chain);
    this.peerIId = requireNonNull(peerIId);
    this.effRibTables = this.peerIId.node(EFFRIBIN_NID);
    this.prefixesInstalled = buildPrefixesTables(tables);
    this.prefixesReceived = buildPrefixesTables(tables);
    this.ribPolicies = requireNonNull(rib.getRibPolicies());
    this.service = requireNonNull(rib.getService());
    this.tableTypeRegistry = requireNonNull(tableTypeRegistry);
    this.peerImportParameters = peer;
    this.rtMemberships = rtMemberships;
    this.rtCache = rtCache;
    this.vpnTableRefresher = rib;
}
 
Example #9
Source File: AdjRibInWriter.java    From bgpcep with Eclipse Public License 1.0 6 votes vote down vote up
private static void installAdjRibsOutTables(final YangInstanceIdentifier newPeerPath, final RIBSupportContext rs,
        final NodeIdentifierWithPredicates instanceIdentifierKey, final TablesKey tableKey,
        final SendReceive sendReceive, final DOMDataTreeWriteTransaction tx) {
    final NodeIdentifierWithPredicates supTablesKey = RibSupportUtils.toYangKey(SupportedTables.QNAME, tableKey);
    final DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> tt =
            Builders.mapEntryBuilder().withNodeIdentifier(supTablesKey);
    for (final Entry<QName, Object> e : supTablesKey.entrySet()) {
        tt.withChild(ImmutableNodes.leafNode(e.getKey(), e.getValue()));
    }
    if (sendReceive != null) {
        tt.withChild(ImmutableNodes.leafNode(SEND_RECEIVE, sendReceive.toString().toLowerCase(Locale.ENGLISH)));
    }
    tx.put(LogicalDatastoreType.OPERATIONAL, newPeerPath.node(PEER_TABLES).node(supTablesKey), tt.build());
    rs.createEmptyTableStructure(tx, newPeerPath.node(EMPTY_ADJRIBOUT.getIdentifier())
            .node(TABLES_NID).node(instanceIdentifierKey));
}
 
Example #10
Source File: ImmutableNodes.java    From yangtools with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Convert YangInstanceIdentifier into a normalized node structure.
 *
 * @param ctx schema context to used during serialization
 * @param id instance identifier to convert to node structure starting from root
 * @param deepestElement pre-built deepest child that will be inserted at the last path argument of provided
 *                       instance identifier
 * @return serialized normalized node for provided instance Id with (optionally) overridden last child
 *         and (optionally) marked with specific operation attribute.
 */
public static @NonNull NormalizedNode<?, ?> fromInstanceId(final SchemaContext ctx, final YangInstanceIdentifier id,
        final Optional<NormalizedNode<?, ?>> deepestElement) {
    final PathArgument topLevelElement;
    final InstanceIdToNodes<?> instanceIdToNodes;
    final Iterator<PathArgument> it = id.getPathArguments().iterator();
    if (it.hasNext()) {
        topLevelElement = it.next();
        final DataSchemaNode dataChildByName = ctx.getDataChildByName(topLevelElement.getNodeType());
        checkNotNull(dataChildByName,
            "Cannot find %s node in schema context. Instance identifier has to start from root", topLevelElement);
        instanceIdToNodes = InstanceIdToNodes.fromSchemaAndQNameChecked(ctx, topLevelElement.getNodeType());
    } else {
        topLevelElement = SCHEMACONTEXT_NAME;
        instanceIdToNodes = InstanceIdToNodes.fromDataSchemaNode(ctx);
    }

    return instanceIdToNodes.create(topLevelElement, it, deepestElement);
}
 
Example #11
Source File: DerefXPathFunctionTest.java    From yangtools with Eclipse Public License 1.0 6 votes vote down vote up
private static ContainerNode buildMyContainerNodeForIIdTest(final LeafNode<?> referencedLeafNode) {
    final Map<QName, Object> keyValues = ImmutableMap.of(KEY_LEAF_A, "key-value-a", KEY_LEAF_B, "key-value-b");
    final YangInstanceIdentifier iidPath = YangInstanceIdentifier.of(MY_CONTAINER).node(MY_LIST)
            .node(NodeIdentifierWithPredicates.of(MY_LIST, keyValues)).node(REFERENCED_LEAF);

    final LeafNode<?> iidLeafNode = Builders.leafBuilder().withNodeIdentifier(new NodeIdentifier(IID_LEAF))
            .withValue(iidPath).build();

    final MapNode myListNode = Builders.mapBuilder().withNodeIdentifier(new NodeIdentifier(MY_LIST))
            .withChild(Builders.mapEntryBuilder().withNodeIdentifier(
                    NodeIdentifierWithPredicates.of(MY_LIST, keyValues))
                    .withChild(iidLeafNode)
                    .withChild(referencedLeafNode).build())
            .build();

    final ContainerNode myContainerNode = Builders.containerBuilder().withNodeIdentifier(
            new NodeIdentifier(MY_CONTAINER)).withChild(myListNode).build();
    return myContainerNode;
}
 
Example #12
Source File: InMemoryDataTreeModification.java    From yangtools with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public Optional<NormalizedNode<?, ?>> readNode(final YangInstanceIdentifier path) {
    /*
     * Walk the tree from the top, looking for the first node between root and
     * the requested path which has been modified. If no such node exists,
     * we use the node itself.
     */
    final Entry<YangInstanceIdentifier, ModifiedNode> entry = StoreTreeNodes.findClosestsOrFirstMatch(rootNode,
        path, ModifiedNode.IS_TERMINAL_PREDICATE);
    final YangInstanceIdentifier key = entry.getKey();
    final ModifiedNode mod = entry.getValue();

    final Optional<? extends TreeNode> result = resolveSnapshot(key, mod);
    if (result.isPresent()) {
        final NormalizedNode<?, ?> data = result.get().getData();
        return NormalizedNodes.findNode(key, data, path);
    }

    return Optional.empty();
}
 
Example #13
Source File: AdjRibInWriter.java    From bgpcep with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Create new table instances, potentially creating their empty entries.
 */
private static ImmutableMap<TablesKey, TableContext> createNewTableInstances(
        final YangInstanceIdentifier newPeerPath, final RIBSupportContextRegistry registry,
        final Set<TablesKey> tableTypes, final Map<TablesKey, SendReceive> addPathTablesType,
        final DOMDataTreeWriteTransaction tx) {

    final Builder<TablesKey, TableContext> tb = ImmutableMap.builder();
    for (final TablesKey tableKey : tableTypes) {
        final RIBSupportContext rs = registry.getRIBSupportContext(tableKey);
        // TODO: Use returned value once Instance Identifier builder allows for it.
        final NodeIdentifierWithPredicates instanceIdentifierKey = RibSupportUtils.toYangTablesKey(tableKey);
        if (rs == null) {
            LOG.warn("No support for table type {}, skipping it", tableKey);
            continue;
        }
        installAdjRibsOutTables(newPeerPath, rs, instanceIdentifierKey, tableKey,
                addPathTablesType.get(tableKey), tx);
        installAdjRibInTables(newPeerPath, tableKey, rs, instanceIdentifierKey, tx, tb);
    }
    return tb.build();
}
 
Example #14
Source File: StoreTreeNodes.java    From yangtools with Eclipse Public License 1.0 6 votes vote down vote up
public static <T extends StoreTreeNode<T>> Entry<YangInstanceIdentifier, T> findClosestsOrFirstMatch(final T tree,
        final YangInstanceIdentifier path, final Predicate<T> predicate) {
    Optional<? extends T> parent = Optional.of(tree);
    Optional<? extends T> current = Optional.of(tree);

    int nesting = 0;
    Iterator<PathArgument> pathIter = path.getPathArguments().iterator();
    while (current.isPresent() && pathIter.hasNext() && !predicate.test(current.get())) {
        parent = current;
        current = current.get().getChild(pathIter.next());
        nesting++;
    }
    if (current.isPresent()) {
        final YangInstanceIdentifier currentPath = path.getAncestor(nesting);
        return new SimpleImmutableEntry<>(currentPath, current.get());
    }

    /*
     * Subtracting 1 from nesting level at this point is safe, because we
     * cannot reach here with nesting == 0: that would mean the above check
     * for current.isPresent() failed, which it cannot, as current is always
     * present. At any rate we verify state just to be on the safe side.
     */
    verify(nesting > 0);
    return new SimpleImmutableEntry<>(path.getAncestor(nesting - 1), parent.get());
}
 
Example #15
Source File: DataTreeCandidateNodes.java    From yangtools with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Applies the {@code node} that is rooted(doesn't have an identifier) in tree A to tree B's {@code cursor}
 * at location specified by {@code rootPath}.
 *
 * @param cursor cursor from the modification we want to apply the {@code node} to
 * @param rootPath path in the {@code cursor}'s tree we want to apply to candidate to
 * @param node candidate tree to apply
 */
public static void applyRootedNodeToCursor(final DataTreeModificationCursor cursor,
        final YangInstanceIdentifier rootPath, final DataTreeCandidateNode node) {
    switch (node.getModificationType()) {
        case DELETE:
            cursor.delete(rootPath.getLastPathArgument());
            break;
        case SUBTREE_MODIFIED:
            cursor.enter(rootPath.getLastPathArgument());
            AbstractNodeIterator iterator = new ExitingNodeIterator(null, node.getChildNodes().iterator());
            do {
                iterator = iterator.next(cursor);
            } while (iterator != null);
            break;
        case UNMODIFIED:
            // No-op
            break;
        case WRITE:
            cursor.write(rootPath.getLastPathArgument(), node.getDataAfter().get());
            break;
        default:
            throw new IllegalArgumentException("Unsupported modification " + node.getModificationType());
    }
}
 
Example #16
Source File: YT776Test.java    From yangtools with Eclipse Public License 1.0 6 votes vote down vote up
@Test
public void testDisappearInChoice() throws DataValidationFailedException {
    DataTreeModification mod = dataTree.takeSnapshot().newModification();
    // Initialize choice with list
    mod.write(YangInstanceIdentifier.create(BOX), containerBuilder().withNodeIdentifier(BOX)
        .withChild(choiceBuilder().withNodeIdentifier(ANY_OF)
            .withChild(mapBuilder().withNodeIdentifier(SOME_LIST_ID)
                .withChild(mapEntryBuilder()
                    .withNodeIdentifier(SOME_LIST_ITEM)
                    .withChild(leafBuilder().withNodeIdentifier(SOME_LEAF_ID).withValue("foo").build())
                    .build())
                .build())
            .build())
        .build());
    commit(mod);

    // Now delete the single item, causing the list to fizzle, while creating the alterinative case
    mod = dataTree.takeSnapshot().newModification();
    mod.delete(YangInstanceIdentifier.create(BOX, ANY_OF, SOME_LIST_ID, SOME_LIST_ITEM));
    mod.write(YangInstanceIdentifier.create(BOX, ANY_OF, SOME_LEAF_ID),
        leafBuilder().withNodeIdentifier(SOME_LEAF_ID).withValue("foo").build());

    commit(mod);
}
 
Example #17
Source File: XMLStreamWriterUtils.java    From yangtools with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Write a value into a XML stream writer. This method assumes the start and end of element is
 * emitted by the caller.
 *
 * @param writer XML Stream writer
 * @param type data type. In case of leaf ref this should be the type of leaf being referenced
 * @param value data value
 * @param parent optional parameter of a module QName owning the leaf definition
 * @return String characters to be written
 * @throws XMLStreamException if an encoding problem occurs
 */
private String encodeValue(final @NonNull ValueWriter writer, final @NonNull TypeDefinition<?> type,
        final @NonNull Object value, final QNameModule parent) throws XMLStreamException {
    if (type instanceof IdentityrefTypeDefinition) {
        return encode(writer, (IdentityrefTypeDefinition) type, value, parent);
    } else if (type instanceof InstanceIdentifierTypeDefinition) {
        return encode(writer, (InstanceIdentifierTypeDefinition) type, value);
    } else if (value instanceof QName && isIdentityrefUnion(type)) {
        // Ugly special-case form unions with identityrefs
        return encode(writer, (QName) value, parent);
    } else if (value instanceof YangInstanceIdentifier && isInstanceIdentifierUnion(type)) {
        return encodeInstanceIdentifier(writer, (YangInstanceIdentifier) value);
    } else {
        return serialize(type, value);
    }
}
 
Example #18
Source File: InMemoryDataTreeFactory.java    From yangtools with Eclipse Public License 1.0 6 votes vote down vote up
private static @NonNull NormalizedNode<?, ?> createRoot(final DataNodeContainer schemaNode,
        final YangInstanceIdentifier path) {
    if (path.isEmpty()) {
        checkArgument(schemaNode instanceof ContainerSchemaNode,
            "Conceptual tree root has to be a container, not %s", schemaNode);
        return ROOT_CONTAINER;
    }

    final PathArgument arg = path.getLastPathArgument();
    if (schemaNode instanceof ContainerSchemaNode) {
        checkArgument(arg instanceof NodeIdentifier, "Mismatched container %s path %s", schemaNode, path);
        return ImmutableContainerNodeBuilder.create().withNodeIdentifier((NodeIdentifier) arg).build();
    } else if (schemaNode instanceof ListSchemaNode) {
        // This can either be a top-level list or its individual entry
        if (arg instanceof NodeIdentifierWithPredicates) {
            return ImmutableNodes.mapEntryBuilder().withNodeIdentifier((NodeIdentifierWithPredicates) arg).build();
        }
        checkArgument(arg instanceof NodeIdentifier, "Mismatched list %s path %s", schemaNode, path);
        return ImmutableNodes.mapNodeBuilder().withNodeIdentifier((NodeIdentifier) arg).build();
    } else {
        throw new IllegalArgumentException("Unsupported root schema " + schemaNode);
    }
}
 
Example #19
Source File: AdjRibsInWriterTest.java    From bgpcep with Eclipse Public License 1.0 5 votes vote down vote up
@Before
public void setUp() {
    MockitoAnnotations.initMocks(this);
    doReturn("MockedTrans").when(this.tx).toString();
    doReturn(this.tx).when(this.chain).newWriteOnlyTransaction();
    doReturn(CommitInfo.emptyFluentFuture()).when(this.tx).commit();
    doNothing().when(this.tx).put(eq(LogicalDatastoreType.OPERATIONAL),
            any(YangInstanceIdentifier.class), any(NormalizedNode.class));
    doNothing().when(this.tx).merge(eq(LogicalDatastoreType.OPERATIONAL),
            any(YangInstanceIdentifier.class), any(NormalizedNode.class));
    doReturn(this.context).when(this.registry).getRIBSupportContext(any(TablesKey.class));
    doReturn(this.chain).when(this.ptc).getDomChain();
    doNothing().when(this.context).createEmptyTableStructure(eq(this.tx), any(YangInstanceIdentifier.class));
}
 
Example #20
Source File: Bug5968MergeTest.java    From yangtools with Eclipse Public License 1.0 5 votes vote down vote up
private static void mergeMapEntry(final DataTreeModification modificationTree, final Object listIdValue,
        final Object mandatoryLeafValue, final Object commonLeafValue) throws DataValidationFailedException {
    final MapEntryNode taskEntryNode = mandatoryLeafValue == null ? createMapEntry(listIdValue, commonLeafValue)
            : createMapEntry(listIdValue, mandatoryLeafValue, commonLeafValue);

    modificationTree.merge(
            YangInstanceIdentifier.of(ROOT).node(MY_LIST)
                    .node(NodeIdentifierWithPredicates.of(MY_LIST, ImmutableMap.of(LIST_ID, listIdValue))),
            taskEntryNode);
}
 
Example #21
Source File: DataTreeCandidateValidatorTest3.java    From yangtools with Eclipse Public License 1.0 5 votes vote down vote up
private static void writeDevices() throws DataValidationFailedException {
    final ContainerSchemaNode devicesContSchemaNode = (ContainerSchemaNode) mainModule.findDataChildByName(devices)
            .get();
    final ContainerNode devicesContainer = createDevicesContainer(devicesContSchemaNode);
    final YangInstanceIdentifier devicesPath = YangInstanceIdentifier.of(devices);
    final DataTreeModification writeModification = inMemoryDataTree.takeSnapshot().newModification();
    writeModification.write(devicesPath, devicesContainer);

    writeModification.ready();
    final DataTreeCandidate writeDevicesCandidate = inMemoryDataTree.prepare(writeModification);

    LOG.debug("*************************");
    LOG.debug("Before writeDevices: ");
    LOG.debug("*************************");
    LOG.debug("{}", inMemoryDataTree);

    boolean exception = false;
    try {
        LeafRefValidation.validate(writeDevicesCandidate, rootLeafRefContext);
    } catch (final LeafRefDataValidationFailedException e) {
        LOG.debug("All validation errors:{}{}", NEW_LINE, e.getMessage());
        assertEquals(6, e.getValidationsErrorsCount());
        exception = true;
    }

    assertTrue(exception);

    inMemoryDataTree.commit(writeDevicesCandidate);

    LOG.debug("*************************");
    LOG.debug("After writeDevices: ");
    LOG.debug("*************************");
    LOG.debug("{}", inMemoryDataTree);
}
 
Example #22
Source File: Bug5968MergeTest.java    From yangtools with Eclipse Public License 1.0 5 votes vote down vote up
@Test
public void invalidMultiStepsMergeTest() throws DataValidationFailedException {
    final DataTree inMemoryDataTree = emptyDataTree(SCHEMA_CONTEXT);
    final DataTreeModification modificationTree = inMemoryDataTree.takeSnapshot().newModification();

    modificationTree.merge(YangInstanceIdentifier.of(ROOT), createContainerBuilder().build());
    modificationTree.merge(YangInstanceIdentifier.of(ROOT).node(MY_LIST), createMapBuilder().build());
    modificationTree.merge(
            YangInstanceIdentifier.of(ROOT).node(MY_LIST)
                    .node(NodeIdentifierWithPredicates.of(MY_LIST, ImmutableMap.of(LIST_ID, "1"))),
            createEmptyMapEntryBuilder("1").build());
    modificationTree.merge(
            YangInstanceIdentifier.of(ROOT).node(MY_LIST)
                    .node(NodeIdentifierWithPredicates.of(MY_LIST, ImmutableMap.of(LIST_ID, "1"))),
            createMapEntry("1", "common-value"));

    try {
        modificationTree.ready();
        inMemoryDataTree.validate(modificationTree);
        final DataTreeCandidate prepare = inMemoryDataTree.prepare(modificationTree);
        inMemoryDataTree.commit(prepare);
        fail("Should fail due to missing mandatory leaf.");
    } catch (final IllegalArgumentException e) {
        assertEquals(
                "Node (foo?revision=2016-07-28)my-list[{(foo?revision=2016-07-28)list-id=1}] is missing mandatory "
                        + "descendant /(foo?revision=2016-07-28)mandatory-leaf", e.getMessage());
    }
}
 
Example #23
Source File: StoreTreeNodesTest.java    From yangtools with Eclipse Public License 1.0 5 votes vote down vote up
private static ContainerNode createTestContainer() {
    return ImmutableContainerNodeBuilder
            .create()
            .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(TestModel.TEST_QNAME))
            .withChild(
                    mapNodeBuilder(TestModel.OUTER_LIST_QNAME)
                    .withChild(mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, ONE_ID))
                    .withChild(BAR_NODE).build()).build();
}
 
Example #24
Source File: JaxenTest.java    From yangtools with Eclipse Public License 1.0 5 votes vote down vote up
@Before
public void setup() throws XPathExpressionException {
    final SchemaContext schemaContext = YangParserTestUtils.parseYangResourceDirectory("/test/documentTest");
    assertNotNull(schemaContext);

    initQNames();
    xpathSchemaContext = new JaxenSchemaContextFactory().createContext(schemaContext);
    assertNotNull(xpathSchemaContext);

    xpathExpression = xpathSchemaContext.compileExpression(createSchemaPath(), createPrefixes(), createXPath(
                false));
    assertNotNull(xpathExpression);

    xpathDocument = xpathSchemaContext.createDocument(TestUtils.createNormalizedNodes());
    assertNotNull(xpathDocument);
    String rootNodeName = xpathDocument.getRootNode().getNodeType().getLocalName();
    assertNotNull(rootNodeName);
    assertEquals("root", rootNodeName);

    Optional<? extends XPathResult<?>> resultExpressionEvaluate = xpathExpression
            .evaluate(xpathDocument, createYangInstanceIdentifier(false));
    assertNotNull(resultExpressionEvaluate);
    assertTrue(resultExpressionEvaluate.isPresent());
    XPathResult<?> xpathResult = resultExpressionEvaluate.get();
    assertTrue(xpathResult instanceof XPathNodesetResult);
    XPathNodesetResult nodeset = (XPathNodesetResult) xpathResult;

    Entry<YangInstanceIdentifier, NormalizedNode<?, ?>> entry = nodeset.getValue().iterator().next();
    assertNotNull(entry);
    assertEquals("three", entry.getValue().getValue());

    convertNctx = new ConverterNamespaceContext(createPrefixes());
    navigator = new NormalizedNodeNavigator(convertNctx, (JaxenDocument) xpathDocument);
    assertNotNull(navigator);
}
 
Example #25
Source File: AbstractMagnesiumDataInput.java    From yangtools with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public final YangInstanceIdentifier readYangInstanceIdentifier() throws IOException {
    final byte type = input.readByte();
    if (type == MagnesiumValue.YIID) {
        return readYangInstanceIdentifier(input.readInt());
    } else if (type >= MagnesiumValue.YIID_0) {
        // Note 'byte' is range limited, so it is always '&& type <= MagnesiumValue.YIID_31'
        return readYangInstanceIdentifier(type - MagnesiumValue.YIID_0);
    } else {
        throw new InvalidNormalizedNodeStreamException("Unexpected YangInstanceIdentifier type " + type);
    }
}
 
Example #26
Source File: RIBSupportContextImpl.java    From bgpcep with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public Collection<NodeIdentifierWithPredicates> writeRoutes(final DOMDataTreeWriteTransaction tx,
                                                            final YangInstanceIdentifier tableId,
                                                            final MpReachNlri nlri,
                                                            final Attributes attributes) {
    final ContainerNode domNlri = this.codecs.serializeReachNlri(nlri);
    final ContainerNode routeAttributes = this.codecs.serializeAttributes(attributes);
    return this.ribSupport.putRoutes(tx, tableId, domNlri, routeAttributes);
}
 
Example #27
Source File: InMemoryDataTreeModification.java    From yangtools with Eclipse Public License 1.0 5 votes vote down vote up
private void checkIdentifierReferencesData(final YangInstanceIdentifier path,
        final NormalizedNode<?, ?> data) {
    final PathArgument arg;

    if (!path.isEmpty()) {
        arg = path.getLastPathArgument();
        checkArgument(arg != null, "Instance identifier %s has invalid null path argument", path);
    } else {
        arg = rootNode.getIdentifier();
    }

    checkIdentifierReferencesData(arg, data);
}
 
Example #28
Source File: FlowspecL3vpnIpv6RIBSupportTest.java    From bgpcep with Eclipse Public License 1.0 5 votes vote down vote up
@Test
public void testRoutePath() {
    final YangInstanceIdentifier.NodeIdentifierWithPredicates prefixNii = createRouteNIWP(
        new FlowspecL3vpnIpv6RoutesBuilder().setFlowspecL3vpnRoute(Map.of(ROUTE.key(), ROUTE)).build());
    Assert.assertEquals(getRoutePath().node(prefixNii),
            this.ribSupport.routePath(getTablePath(), prefixNii));
}
 
Example #29
Source File: OrderedListTest.java    From yangtools with Eclipse Public License 1.0 5 votes vote down vote up
public void modification2() throws DataValidationFailedException {
    OrderedMapNode parentOrderedListNode = Builders.orderedMapBuilder().withNodeIdentifier(
            new NodeIdentifier(parentOrderedList))
            .withChild(createParentOrderedListEntry("pkval3", "plfval3updated"))
            .withChild(createParentOrderedListEntry("pkval4", "plfval4"))
            .withChild(createParentOrderedListEntry("pkval5", "plfval5")).build();

    ContainerNode parentContainerNode = Builders.containerBuilder().withNodeIdentifier(
            new NodeIdentifier(parentContainer)).withChild(Builders.containerBuilder()
            .withNodeIdentifier(new NodeIdentifier(childContainer)).withChild(parentOrderedListNode).build())
            .build();

    DataTreeModification treeModification = inMemoryDataTree.takeSnapshot().newModification();

    YangInstanceIdentifier path1 = YangInstanceIdentifier.of(parentContainer);
    treeModification.merge(path1, parentContainerNode);

    OrderedMapNode childOrderedListNode = Builders.orderedMapBuilder().withNodeIdentifier(
            new NodeIdentifier(childOrderedList))
            .withChild(createChildOrderedListEntry("chkval1", "chlfval1updated"))
            .withChild(createChildOrderedListEntry("chkval2", "chlfval2updated"))
            .withChild(createChildOrderedListEntry("chkval3", "chlfval3")).build();

    YangInstanceIdentifier path2 = YangInstanceIdentifier.of(parentContainer).node(childContainer)
            .node(parentOrderedList).node(createParentOrderedListEntryPath("pkval2")).node(childOrderedList);
    treeModification.merge(path2, childOrderedListNode);

    treeModification.ready();
    inMemoryDataTree.validate(treeModification);
    inMemoryDataTree.commit(inMemoryDataTree.prepare(treeModification));

    DataTreeSnapshot snapshotAfterCommits = inMemoryDataTree.takeSnapshot();
    Optional<NormalizedNode<?, ?>> readNode = snapshotAfterCommits.readNode(path1);
    assertTrue(readNode.isPresent());

    readNode = snapshotAfterCommits.readNode(path2);
    assertTrue(readNode.isPresent());
}
 
Example #30
Source File: InMemoryDataTreeModification.java    From yangtools with Eclipse Public License 1.0 5 votes vote down vote up
@SuppressWarnings("checkstyle:illegalCatch")
private Optional<? extends TreeNode> resolveSnapshot(final YangInstanceIdentifier path,
        final ModifiedNode modification) {
    final Optional<? extends TreeNode> potentialSnapshot = modification.getSnapshot();
    if (potentialSnapshot != null) {
        return potentialSnapshot;
    }

    try {
        return resolveModificationStrategy(path).apply(modification, modification.getOriginal(), version);
    } catch (final Exception e) {
        LOG.error("Could not create snapshot for {}:{}", path, modification, e);
        throw e;
    }
}