Search in sources :

Example 91 with EffectiveModelContext

use of org.opendaylight.yangtools.yang.model.api.EffectiveModelContext in project lighty-netconf-simulator by PANTHEONtech.

the class EditConfigRequestProcessor method executeOkRequest.

@SuppressWarnings("checkstyle:FallThrough")
@Override
protected CompletableFuture<Response> executeOkRequest(final Element requestXmlElement) {
    final Optional<DefaultOperation> defaultOperation = RPCUtil.retrieveDefaultOperation(requestXmlElement);
    final Optional<Operation> operation = RPCUtil.retrieveOperation(requestXmlElement);
    Operation operationToExecute;
    if (operation.isPresent()) {
        operationToExecute = operation.get();
    } else {
        if (defaultOperation.isPresent()) {
            if (defaultOperation.get() == DefaultOperation.NONE) {
                throw new IllegalStateException("Operation was " + DefaultOperation.NONE + " or not defined!");
            } else {
                operationToExecute = Operation.getOperationByName(defaultOperation.get().getOperationName());
            }
        } else {
            operationToExecute = Operation.MERGE;
        }
    }
    final Element configElement = (Element) requestXmlElement.getElementsByTagNameNS(Config.QNAME.getNamespace().toString(), Config.QNAME.getLocalName()).item(0);
    final String configString = RPCUtil.formatXml(configElement);
    NormalizedNode configNN;
    try {
        configNN = getNetconfDeviceServices().getXmlNodeConverter().deserialize(getNetconfDeviceServices().getRootSchemaNode(), new StringReader(configString));
    } catch (final DeserializationException e) {
        return CompletableFuture.completedFuture(new ResponseErrorMessage(new NetconfDocumentedException("operation-failed", ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED, ErrorSeverity.ERROR)));
    }
    EffectiveModelContext effectiveModelContext = getNetconfDeviceServices().getAdapterContext().currentSerializer().getRuntimeContext().getEffectiveModelContext();
    YangInstanceIdentifier path = retrieveElementYII(effectiveModelContext, configNN, configElement, "//*[@*[local-name() = 'operation']]");
    NormalizedNode data;
    if (path == null) {
        Optional<DataContainerChild> optionalData = ((AbstractCollection<DataContainerChild>) configNN.body()).stream().findFirst();
        if (optionalData.isEmpty()) {
            return CompletableFuture.completedFuture(new ResponseErrorMessage(new NetconfDocumentedException("data-missing", ErrorType.APPLICATION, ErrorTag.DATA_MISSING, ErrorSeverity.ERROR)));
        }
        data = optionalData.get();
        path = YangInstanceIdentifier.builder().node(data.getIdentifier().getNodeType()).build();
    } else {
        Optional<NormalizedNode> optionalData = NormalizedNodes.findNode(configNN, path);
        if (optionalData.isEmpty()) {
            return CompletableFuture.completedFuture(new ResponseErrorMessage(new NetconfDocumentedException("data-missing", ErrorType.APPLICATION, ErrorTag.DATA_MISSING, ErrorSeverity.ERROR)));
        }
        data = optionalData.get();
    }
    final DOMDataTreeWriteTransaction writeTx = getNetconfDeviceServices().getDOMDataBroker().newWriteOnlyTransaction();
    final CompletableFuture<Response> responseFuture = new CompletableFuture<>();
    switch(operationToExecute) {
        case CREATE:
            if (dataExists(path, operationToExecute, data)) {
                final NetconfDocumentedException netconfDocumentedException = new NetconfDocumentedException("data-exists", ErrorType.RPC, ErrorTag.DATA_EXISTS, ErrorSeverity.ERROR);
                responseFuture.complete(new ResponseErrorMessage(netconfDocumentedException));
                return responseFuture;
            }
        case REPLACE:
            ensureParentsByMerge(path, writeTx);
            writeTx.put(LogicalDatastoreType.CONFIGURATION, path, data);
            break;
        case DELETE:
            if (!dataExists(path, operationToExecute, data)) {
                final NetconfDocumentedException netconfDocumentedException = new NetconfDocumentedException("data-missing", ErrorType.RPC, ErrorTag.DATA_MISSING, ErrorSeverity.ERROR);
                responseFuture.complete(new ResponseErrorMessage(netconfDocumentedException));
                return responseFuture;
            }
        case REMOVE:
            writeTx.delete(LogicalDatastoreType.CONFIGURATION, path);
            break;
        case MERGE:
            writeTx.merge(LogicalDatastoreType.CONFIGURATION, path, data);
            break;
        default:
            break;
    }
    try {
        writeTx.commit().get(TimeoutUtil.TIMEOUT_MILLIS, TimeUnit.MILLISECONDS);
        responseFuture.complete(new ResponseData(Collections.emptyList()));
        return responseFuture;
    } catch (InterruptedException | ExecutionException | TimeoutException e) {
        if (e instanceof InterruptedException) {
            Thread.currentThread().interrupt();
        }
        if (e.getCause() instanceof TransactionCommitFailedException) {
            final Throwable error = e.getCause();
            if (error.getCause() instanceof SchemaValidationFailedException) {
                final NetconfDocumentedException netconfDocumentedException = new NetconfDocumentedException(error.getCause().getMessage(), ErrorType.APPLICATION, ErrorTag.BAD_ELEMENT, ErrorSeverity.ERROR);
                responseFuture.complete(new ResponseErrorMessage(netconfDocumentedException));
                return responseFuture;
            }
        }
        throw createTxException(data, e, operationToExecute.getOperationName().toUpperCase(Locale.ROOT));
    }
}
Also used : Element(org.w3c.dom.Element) NetconfDocumentedException(org.opendaylight.netconf.api.NetconfDocumentedException) DefaultOperation(io.lighty.netconf.device.utils.DefaultOperation) Operation(io.lighty.netconf.device.utils.Operation) DeserializationException(io.lighty.codecs.util.exception.DeserializationException) TransactionCommitFailedException(org.opendaylight.mdsal.common.api.TransactionCommitFailedException) CompletableFuture(java.util.concurrent.CompletableFuture) DefaultOperation(io.lighty.netconf.device.utils.DefaultOperation) DataContainerChild(org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild) StringReader(java.io.StringReader) NormalizedNode(org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode) ExecutionException(java.util.concurrent.ExecutionException) TimeoutException(java.util.concurrent.TimeoutException) ResponseErrorMessage(io.lighty.netconf.device.response.ResponseErrorMessage) DOMDataTreeWriteTransaction(org.opendaylight.mdsal.dom.api.DOMDataTreeWriteTransaction) ResponseData(io.lighty.netconf.device.response.ResponseData) YangInstanceIdentifier(org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier) SchemaValidationFailedException(org.opendaylight.yangtools.yang.data.impl.schema.tree.SchemaValidationFailedException) Response(io.lighty.netconf.device.response.Response) EffectiveModelContext(org.opendaylight.yangtools.yang.model.api.EffectiveModelContext)

Example 92 with EffectiveModelContext

use of org.opendaylight.yangtools.yang.model.api.EffectiveModelContext in project yangtools by opendaylight.

the class Bug5830Test method testMultipleContainers.

private static void testMultipleContainers() throws DataValidationFailedException {
    final EffectiveModelContext schemaContext = TestModel.createTestContext("/bug-5830/foo-multiple.yang");
    assertNotNull("Schema context must not be null.", schemaContext);
    testContainerIsNotPresent(schemaContext);
    try {
        testContainerIsPresent(schemaContext);
        fail("Should fail due to missing mandatory node under present presence container.");
    } catch (IllegalArgumentException e) {
        assertTrue(e.getMessage().startsWith("Node (foo?revision=2016-05-17)task-data is missing mandatory descendant"));
    }
    try {
        testMandatoryDataLeafIsPresent(schemaContext);
        fail("Should fail due to missing mandatory node under present presence container.");
    } catch (IllegalArgumentException e) {
        assertEquals("Node (foo?revision=2016-05-17)task-data " + "is missing mandatory descendant /(foo?revision=2016-05-17)non-presence-container/" + "non-presence-container-2/mandatory-leaf-2", e.getMessage());
    }
    testMandatoryLeaf2IsPresent(schemaContext, false);
    try {
        testMandatoryLeaf2IsPresent(schemaContext, true);
        fail("Should fail due to missing mandatory node under present presence container.");
    } catch (IllegalArgumentException e) {
        assertEquals("Node (foo?revision=2016-05-17)presence-container-2 is missing mandatory " + "descendant /(foo?revision=2016-05-17)mandatory-leaf-3", e.getMessage());
    }
}
Also used : EffectiveModelContext(org.opendaylight.yangtools.yang.model.api.EffectiveModelContext)

Example 93 with EffectiveModelContext

use of org.opendaylight.yangtools.yang.model.api.EffectiveModelContext in project yangtools by opendaylight.

the class Bug8713Test method dataTreeCanditateValidationTest.

@Test
public void dataTreeCanditateValidationTest() throws Exception {
    final EffectiveModelContext context = YangParserTestUtils.parseYangResourceDirectory("/bug8713/");
    final LeafRefContext rootLeafRefContext = LeafRefContext.create(context);
    final DataTree inMemoryDataTree = new InMemoryDataTreeFactory().create(DataTreeConfiguration.DEFAULT_OPERATIONAL, context);
    final ContainerNode root = createRootContainer();
    final YangInstanceIdentifier rootPath = YangInstanceIdentifier.of(foo("root"));
    final DataTreeModification writeModification = inMemoryDataTree.takeSnapshot().newModification();
    writeModification.write(rootPath, root);
    writeModification.ready();
    final DataTreeCandidate writeContributorsCandidate = inMemoryDataTree.prepare(writeModification);
    LeafRefValidation.validate(writeContributorsCandidate, rootLeafRefContext);
    inMemoryDataTree.commit(writeContributorsCandidate);
}
Also used : DataTreeModification(org.opendaylight.yangtools.yang.data.tree.api.DataTreeModification) DataTreeCandidate(org.opendaylight.yangtools.yang.data.tree.api.DataTreeCandidate) DataTree(org.opendaylight.yangtools.yang.data.tree.api.DataTree) ContainerNode(org.opendaylight.yangtools.yang.data.api.schema.ContainerNode) YangInstanceIdentifier(org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier) EffectiveModelContext(org.opendaylight.yangtools.yang.model.api.EffectiveModelContext) InMemoryDataTreeFactory(org.opendaylight.yangtools.yang.data.tree.impl.di.InMemoryDataTreeFactory) Test(org.junit.Test)

Example 94 with EffectiveModelContext

use of org.opendaylight.yangtools.yang.model.api.EffectiveModelContext in project yangtools by opendaylight.

the class Bug5830Test method testNonPresenceContainer.

private static void testNonPresenceContainer() throws DataValidationFailedException {
    final EffectiveModelContext schemaContext = TestModel.createTestContext("/bug-5830/foo-non-presence.yang");
    assertNotNull("Schema context must not be null.", schemaContext);
    try {
        testContainerIsNotPresent(schemaContext);
        fail("Should fail due to missing mandatory node.");
    } catch (IllegalArgumentException e) {
        assertEquals("Node (foo?revision=2016-05-17)task[{(foo?revision=2016-05-17)task-id=123}] is missing mandatory " + "descendant /(foo?revision=2016-05-17)task-data/mandatory-data", e.getMessage());
    }
    try {
        testContainerIsPresent(schemaContext);
        fail("Should fail due to missing mandatory node.");
    } catch (IllegalArgumentException e) {
        assertEquals("Node (foo?revision=2016-05-17)task[{(foo?revision=2016-05-17)task-id=123}] is missing mandatory " + "descendant /(foo?revision=2016-05-17)task-data/mandatory-data", e.getMessage());
    }
    testMandatoryDataLeafIsPresent(schemaContext);
}
Also used : EffectiveModelContext(org.opendaylight.yangtools.yang.model.api.EffectiveModelContext)

Example 95 with EffectiveModelContext

use of org.opendaylight.yangtools.yang.model.api.EffectiveModelContext in project yangtools by opendaylight.

the class AbstractYangTest method assertEffectiveModelDir.

@SuppressWarnings("checkstyle:illegalCatch")
@NonNull
public static EffectiveModelContext assertEffectiveModelDir(final String resourceDirName) {
    final EffectiveModelContext ret;
    try {
        ret = TestUtils.loadModules(resourceDirName);
    } catch (Exception e) {
        Throwables.throwIfUnchecked(e);
        throw new AssertionError("Failed to assemble effective model of " + resourceDirName, e);
    }
    assertNotNull(ret);
    return ret;
}
Also used : InferenceException(org.opendaylight.yangtools.yang.parser.spi.meta.InferenceException) SomeModifiersUnresolvedException(org.opendaylight.yangtools.yang.parser.spi.meta.SomeModifiersUnresolvedException) InvalidSubstatementException(org.opendaylight.yangtools.yang.parser.spi.meta.InvalidSubstatementException) SourceException(org.opendaylight.yangtools.yang.parser.spi.source.SourceException) EffectiveModelContext(org.opendaylight.yangtools.yang.model.api.EffectiveModelContext) NonNull(org.eclipse.jdt.annotation.NonNull)

Aggregations

EffectiveModelContext (org.opendaylight.yangtools.yang.model.api.EffectiveModelContext)182 Test (org.junit.Test)99 Module (org.opendaylight.yangtools.yang.model.api.Module)37 QName (org.opendaylight.yangtools.yang.common.QName)29 ContainerNode (org.opendaylight.yangtools.yang.data.api.schema.ContainerNode)28 DataSchemaNode (org.opendaylight.yangtools.yang.model.api.DataSchemaNode)26 NormalizedNode (org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode)24 LeafSchemaNode (org.opendaylight.yangtools.yang.model.api.LeafSchemaNode)24 ContainerSchemaNode (org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode)21 YangInstanceIdentifier (org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier)18 QNameModule (org.opendaylight.yangtools.yang.common.QNameModule)16 NodeIdentifier (org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier)16 NormalizedNodeStreamWriter (org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter)16 IRSchemaSource (org.opendaylight.yangtools.yang.parser.rfc7950.ir.IRSchemaSource)14 DOMMountPoint (org.opendaylight.mdsal.dom.api.DOMMountPoint)13 RestconfDocumentedException (org.opendaylight.restconf.common.errors.RestconfDocumentedException)13 RpcDefinition (org.opendaylight.yangtools.yang.model.api.RpcDefinition)13 MapEntryNode (org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode)11 IOException (java.io.IOException)9 Collection (java.util.Collection)9