Json格式的netconf转成NormalizedNode

背景:

之前发过一篇文章

将NetConf转成NormalizedNode对象及NormalizedNode对象转回NetConf(序列化与反序列化)

请参考该文章的背景

该文章的不足之处在于

无论json还是xml文件都是完整的,但是实际的情况可能是不完整的。

想要将部分的json转成NormalizedNode

第一步:建立Maven工程



    4.0.0

    TestYangTools
    TestYangTools
    1.0-SNAPSHOT
    
        
        
            junit
            junit
            4.12
        

        
        
            org.opendaylight.yangtools
            yang-data-codec-xml
            2.0.16
        

        
        
            org.opendaylight.yangtools
            yang-test-util
            2.0.16
        


        
        
            org.opendaylight.yangtools
            yang-data-codec-gson
            2.0.16
        


        
        
            org.slf4j
            slf4j-api
            1.7.7
        

        
            org.opendaylight.netconf
            restconf-nb-rfc8040
            1.7.4
        


        
            javax.ws.rs
            javax.ws.rs-api
            2.0.1
        

    


第二步:创建文件,编写代码

文件目录如下,target是运行之后的结果

Json格式的netconf转成NormalizedNode_第1张图片

 (1)TestPartOfJson

import com.google.common.io.Resources;
import com.google.gson.stream.JsonReader;
import org.junit.Test;
import org.opendaylight.controller.md.sal.dom.api.DOMMountPoint;
import org.opendaylight.restconf.common.context.InstanceIdentifierContext;
import org.opendaylight.restconf.nb.rfc8040.utils.parser.IdentifierCodec;
import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
import org.opendaylight.yangtools.yang.data.codec.gson.JSONCodecFactorySupplier;
import org.opendaylight.yangtools.yang.data.codec.gson.JsonParserStream;
import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNormalizedNodeStreamWriter;
import org.opendaylight.yangtools.yang.data.impl.schema.NormalizedNodeResult;
import org.opendaylight.yangtools.yang.data.util.DataSchemaContextNode;
import org.opendaylight.yangtools.yang.data.util.DataSchemaContextTree;
import org.opendaylight.yangtools.yang.model.api.*;
import org.opendaylight.yangtools.yang.model.util.SchemaContextUtil;
import org.opendaylight.yangtools.yang.test.util.YangParserTestUtils;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.Iterator;


public class TestPartOfJson {

    @Test
    public void jsonToNormalizedNodeTest() throws IOException {

        String uriPath = "baz:baz/my-container-1/my-leaf-1=value1";
        String jsonPath = "/baz/baz.json";
        String yangFilePath = "/baz/";

        SchemaContext schemaContext = YangParserTestUtils.parseYangResourceDirectory(yangFilePath);

        //第一步:构建InstanceIdentifierContext
        InstanceIdentifierContext instanceIdentifierContext = this.buildInstanceIdentifierContext(uriPath, schemaContext);

        //第二步:加载json文件
        String payload = loadData(jsonPath);
        InputStream entityStream = new ByteArrayInputStream(payload.getBytes(StandardCharsets.UTF_8));

        //第三步:获取NormalizedNode
        NormalizedNode normalizedNode = this.readFrom(instanceIdentifierContext, entityStream, false);

        //第四步:得到NormalizedNode
        System.out.println("NormalizedNode:"+normalizedNode);


    }


    public NormalizedNode readFrom(
            final InstanceIdentifierContext path, InputStream entityStream, final boolean isPost) {

        final NormalizedNodeResult resultHolder = new NormalizedNodeResult();
        final NormalizedNodeStreamWriter writer = ImmutableNormalizedNodeStreamWriter.from(resultHolder);

        final SchemaNode parentSchema;
        if (isPost) {
            parentSchema = path.getSchemaNode();
        } else if (path.getSchemaNode() instanceof SchemaContext) {
            parentSchema = path.getSchemaContext();
        } else {
            if (SchemaPath.ROOT.equals(path.getSchemaNode().getPath().getParent())) {
                parentSchema = path.getSchemaContext();
            } else {
                parentSchema = SchemaContextUtil
                        .findDataSchemaNode(path.getSchemaContext(), path.getSchemaNode().getPath().getParent());
            }
        }

        final JsonParserStream jsonParser = JsonParserStream.create(writer,
                JSONCodecFactorySupplier.RFC7951.getShared(path.getSchemaContext()), parentSchema);
        System.out.println("jsonParser:"+jsonParser);

        final JsonReader reader = new JsonReader(new InputStreamReader(entityStream));
        jsonParser.parse(reader);

        NormalizedNode result = resultHolder.getResult();
        System.out.println("result:"+result);

        return result;
    }

    private static String loadData(final String path) throws IOException {
        return Resources.asCharSource(TestPartOfJson.class.getResource(path),
                StandardCharsets.UTF_8).read();
    }


    public InstanceIdentifierContext buildInstanceIdentifierContext(final String identifier,
                                                                       final SchemaContext schemaContext) {

        YangInstanceIdentifier deserialize = IdentifierCodec.deserialize(identifier, schemaContext);
        DataSchemaContextNode child = DataSchemaContextTree.from(schemaContext).getChild(deserialize);
        if (child != null) {
            return new InstanceIdentifierContext(deserialize, child.getDataSchemaNode(), (DOMMountPoint) null, schemaContext);
        } else {
            QName rpcQName = deserialize.getLastPathArgument().getNodeType();
            RpcDefinition def = null;
            Iterator var7 = ((Module) schemaContext.findModule(rpcQName.getModule()).get()).getRpcs().iterator();

            while (var7.hasNext()) {
                RpcDefinition rpcDefinition = (RpcDefinition) var7.next();
                if (rpcDefinition.getQName().getLocalName().equals(rpcQName.getLocalName())) {
                    def = rpcDefinition;
                    break;
                }
            }

            return new InstanceIdentifierContext(deserialize, def, (DOMMountPoint) null, schemaContext);
        }

    }


}

(2)baz.json

{
   "my-leaf-1":"value1"
}

 (3)baz.yang

module baz {
    namespace "baz";
    prefix baz;

    import yang-ext { prefix ext; revision-date 2013-07-09; }

    container baz {
        container my-container-1 {
            leaf my-leaf-1 {
                type string;
            }
        }

        container my-container-2 {
            container inner-container {
                leaf my-leaf-2 {
                    type string;
                }
            }
            leaf my-leaf-3 {
                type string;
            }
        }

        anyxml my-anyxml-data {
            ext:anyxml-schema-location "/baz/my-container-2";
        }
    }
}

(4)yang-ext.yang

module yang-ext {
    yang-version 1;
    namespace "urn:opendaylight:yang:extension:yang-ext";
    prefix "ext";

    contact "Anton Tkacik ";

    description
        "Copyright (c) 2013 Cisco Systems, Inc. and others. All rights
        reserved. This program and the accompanying materials are made
        available under the terms of the Eclipse Public License v1.0 which
        accompanies this distribution, and is available at http://www.eclipse.org/legal/epl-v10.html";

    revision "2013-07-09" {
        description "";
    }

    // Augmentation name

    extension "augment-identifier" {
        description
                "YANG language extension which assigns an identifier to augmentation.
                Augment identifier is used to identify specific augment statement
                by name. The identifier syntax is defined formally defined by
                the rule 'identifier' in Section 12 of RFC 6020. All augment identifiers
                defined in a namespace MUST be unique. The namespace of augment
                identifiers is shared by module and its submodules.";

        /*
                Discussion:
                This extension allows for ease of development / debug
                of YANG modules and it is suitable for code generation,
                where each augment statement is nicely identified by
                unique name instead of combination of augment target
                and when condition.
            */
        argument "identifier";
    }

    // Context-aware RPCs

    grouping rpc-context-ref {
        description
                "A reference to RPC context.";
        leaf context-instance {
            type instance-identifier;
            description "Pointer to the context. ";
        }
    }

    extension "rpc-context-instance" {
        description
                "YANG language extension which defines enclosing (parent) schema
                node as referencable context for RPCs. The argument is identity
                which is used to identify RPC context type.";

        argument "context-type";
    }

    extension "context-reference" {
        argument "context-type";
    }

    extension "context-instance" {
        argument "context-type";
    }

    extension "instance-target" {
        argument "path";
    }

    extension "anyxml-schema-location" {
        argument "target-node";
    }
}

第三步:运行结果

 

Json格式的netconf转成NormalizedNode_第2张图片

 

你可能感兴趣的:(Yang,json,netconf,NormalizedNode,SDN)