将NetConf转成NormalizedNode对象及NormalizedNode对象转回NetConf(序列化与反序列化)
生活随笔
收集整理的這篇文章主要介紹了
将NetConf转成NormalizedNode对象及NormalizedNode对象转回NetConf(序列化与反序列化)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
背景
我們可以在管理設備的時候可以通過netconf來管理,yangtools給我們提供了一個很好地工具。可以將netconf加載到NormalizedNode對象當中。這樣我們就能夠通過操控NormalizedNode對象,來操控設備。如下圖所示
(yangtools指的是opendaylight中的yangtools,https://github.com/opendaylight)
第一步:建立Maven工程?,配置pom.xml
我的工程命名是:TestYangTools
配置JDK和maven就不贅述了。
maven文件如下
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>TestYangTools</groupId><artifactId>TestYangTools</artifactId><version>1.0-SNAPSHOT</version><dependencies><!--測試--><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.12</version></dependency><!--xml轉NormalizedNode--><dependency><groupId>org.opendaylight.yangtools</groupId><artifactId>yang-data-codec-xml</artifactId><version>2.0.16</version></dependency><!--讀取yang文件--><dependency><groupId>org.opendaylight.yangtools</groupId><artifactId>yang-test-util</artifactId><version>2.0.16</version></dependency><!--json轉NormalizedNode--><dependency><groupId>org.opendaylight.yangtools</groupId><artifactId>yang-data-codec-gson</artifactId><version>2.0.16</version></dependency><!--里面日志,如果不導入無法執行--><dependency><groupId>org.slf4j</groupId><artifactId>slf4j-api</artifactId><version>1.7.7</version></dependency></dependencies></project>?第二步編寫代碼
我的工程文件目錄如下:
?
Mytest文件代碼如下
?我們在代碼中實現了NetConf轉成NormalizedNode對象及NormalizedNode對象轉回NetConf,并輸出結果
package com.kangyucheng;import com.google.common.collect.ImmutableList; import com.google.gson.JsonElement; import com.google.gson.JsonParser; import com.google.gson.stream.JsonReader; import jdk.internal.org.xml.sax.SAXException;import org.junit.Test; import org.opendaylight.yangtools.util.xml.UntrustedXML; import org.opendaylight.yangtools.yang.common.QName; import org.opendaylight.yangtools.yang.common.QNameModule; 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.api.schema.stream.NormalizedNodeWriter; import org.opendaylight.yangtools.yang.data.codec.gson.JSONCodecFactorySupplier; import org.opendaylight.yangtools.yang.data.codec.gson.JSONNormalizedNodeStreamWriter; import org.opendaylight.yangtools.yang.data.codec.gson.JsonParserStream; import org.opendaylight.yangtools.yang.data.codec.gson.JsonWriterFactory; import org.opendaylight.yangtools.yang.data.codec.xml.XMLStreamNormalizedNodeStreamWriter; import org.opendaylight.yangtools.yang.data.codec.xml.XmlParserStream; import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNormalizedNodeStreamWriter; import org.opendaylight.yangtools.yang.data.impl.schema.NormalizedNodeResult; import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode; import org.opendaylight.yangtools.yang.model.api.SchemaContext; import org.opendaylight.yangtools.yang.model.api.SchemaPath; import org.opendaylight.yangtools.yang.model.util.SchemaContextUtil; import org.opendaylight.yangtools.yang.test.util.YangParserTestUtils; import org.w3c.dom.Document; import org.w3c.dom.Node;import javax.xml.parsers.ParserConfigurationException; import javax.xml.stream.XMLOutputFactory; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamReader; import javax.xml.stream.XMLStreamWriter; import javax.xml.transform.*; import javax.xml.transform.dom.DOMResult; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import java.io.*; import java.net.URI; import java.net.URISyntaxException;public class MyTest {private static String loadTextFile(String relativePath) throws IOException, URISyntaxException {File file = new File(MyTest.class.getResource(relativePath).toURI());FileReader fileReader = new FileReader(file);BufferedReader bufReader = new BufferedReader(fileReader);String line = null;StringBuilder result = new StringBuilder();while ((line = bufReader.readLine()) != null) {result.append(line);}bufReader.close();return result.toString();}private static void writeStringToFile(String text, String filePath) {try {FileOutputStream fos = new FileOutputStream(filePath);fos.write(text.getBytes());fos.close();} catch (IOException e) {e.printStackTrace();}}private static Document loadDocument(String xmlPath) throws IOException, org.xml.sax.SAXException {InputStream resourceAsStream = MyTest.class.getResourceAsStream(xmlPath);Document doc = UntrustedXML.newDocumentBuilder().parse(resourceAsStream);doc.getDocumentElement().normalize();return doc;}private static String toString(Node xml) {try {Transformer transformer = TransformerFactory.newInstance().newTransformer();transformer.setOutputProperty(OutputKeys.INDENT, "yes");transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");StreamResult result = new StreamResult(new StringWriter());DOMSource source = new DOMSource(xml);transformer.transform(source, result);return result.getWriter().toString();} catch (IllegalArgumentException | TransformerFactoryConfigurationError | TransformerException e) {throw new RuntimeException("Unable to serialize xml element " + xml, e);}}@Testpublic void jsonToNormalizedNodesTest() throws IOException, URISyntaxException, SAXException {//json轉NormalizedNodeSchemaContext schemaContext = YangParserTestUtils.parseYangResourceDirectory("/baz/");NormalizedNodeResult result = new NormalizedNodeResult();NormalizedNodeStreamWriter streamWriter = ImmutableNormalizedNodeStreamWriter.from(result);JsonParserStream jsonParser = JsonParserStream.create(streamWriter,JSONCodecFactorySupplier.DRAFT_LHOTKA_NETMOD_YANG_JSON_02.getShared(schemaContext));String inputJson = loadTextFile("/baz/baz.json");jsonParser.parse(new JsonReader(new StringReader(inputJson)));NormalizedNode<?, ?> transformedInput = result.getResult();System.out.println("NormalizedNode:"+transformedInput);//NormalizedNode轉jsonWriter writer = new StringWriter();NormalizedNodeStreamWriter jsonStream = JSONNormalizedNodeStreamWriter.createExclusiveWriter(JSONCodecFactorySupplier.DRAFT_LHOTKA_NETMOD_YANG_JSON_02.getShared(schemaContext), SchemaPath.ROOT, null,JsonWriterFactory.createJsonWriter(writer, 2));NormalizedNodeWriter nodeWriter = NormalizedNodeWriter.forStreamWriter(jsonStream);nodeWriter.write(transformedInput);nodeWriter.close();String jsonOutput = writer.toString();writer.toString();JsonParser parser = new JsonParser();JsonElement serializedJson = parser.parse(jsonOutput);System.out.println("序列化json"+serializedJson.toString());//序列化之后的jsonwriteStringToFile(serializedJson.toString(), "newbaz.json");System.out.println("原有json"+inputJson);//原有json}@Testpublic void testXmlToNormalizedNode() throws URISyntaxException, IOException, ParserConfigurationException, SAXException, XMLStreamException, org.xml.sax.SAXException {/*由xml轉NormalizedNode*/QNameModule FOO_MODULE = QNameModule.create(URI.create("foo-namespace"));QName PARENT_CONTAINER = QName.create(FOO_MODULE, "parent-container");SchemaContext schemaContext = YangParserTestUtils.parseYangResourceDirectory("/foo/");ContainerSchemaNode parentContainerSchema = (ContainerSchemaNode) SchemaContextUtil.findNodeInSchemaContext(schemaContext,ImmutableList.of(PARENT_CONTAINER));System.out.println("加載yang:"+schemaContext);InputStream resourceAsStream = MyTest.class.getResourceAsStream("/foo/foo.xml");XMLStreamReader reader = UntrustedXML.createXMLStreamReader(resourceAsStream);NormalizedNodeResult result = new NormalizedNodeResult();NormalizedNodeStreamWriter streamWriter = ImmutableNormalizedNodeStreamWriter.from(result);XmlParserStream xmlParser = XmlParserStream.create(streamWriter, schemaContext, parentContainerSchema);xmlParser.parse(reader);NormalizedNode<?, ?> transformedInput = result.getResult();System.out.println("NormalizedNode:"+transformedInput);/*由NormalizedNode轉xml*/// SchemaContext schemaContext = YangParserTestUtils.parseYangResourceDirectory("/");Document doc = loadDocument("/foo/foo.xml");DOMResult domResult = new DOMResult(UntrustedXML.newDocumentBuilder().newDocument());XMLOutputFactory factory = XMLOutputFactory.newFactory();XMLStreamWriter xmlStreamWriter = factory.createXMLStreamWriter(domResult);NormalizedNodeStreamWriter xmlNormalizedNodeStreamWriter = XMLStreamNormalizedNodeStreamWriter.create(xmlStreamWriter, schemaContext);NormalizedNodeWriter normalizedNodeWriter = NormalizedNodeWriter.forStreamWriter(xmlNormalizedNodeStreamWriter);// normalizedNodeWriter.write(buildOuterContainerNode());//此處可以通過一個函數構建normalizedNodeWriter.write(transformedInput);String expectedXml = toString(doc.getDocumentElement());//為了比較String serializedXml = toString(domResult.getNode());//序列化之后的System.out.println("原有xml:"+expectedXml);//為了比較writeStringToFile(serializedXml.toString(), "newfoo.xml");System.out.println("序列化之后xml:"+serializedXml);//序列化之后的} }兩個Test分別是測試json和xml的
baz文件夾:
這里面的文件都來自于opendaylight提供的源碼中拷貝出來
baz.json
{"baz:baz":{"my-container-1":{"my-leaf-1":"value1"},"my-container-2":{"inner-container":{"my-leaf-2":"value2"},"my-leaf-3":"value3"},"my-anyxml-data":{"inner-container":{"my-leaf-2":"any-xml-leaf-2-value"},"my-leaf-3":"any-xml-leaf-3-value"}} }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";}} }yang-ext.yang
module yang-ext {yang-version 1;namespace "urn:opendaylight:yang:extension:yang-ext";prefix "ext";contact "Anton Tkacik <ttkacik@cisco.com>";description"Copyright (c) 2013 Cisco Systems, Inc. and others. All rightsreserved. This program and the accompanying materials are madeavailable under the terms of the Eclipse Public License v1.0 whichaccompanies this distribution, and is available at http://www.eclipse.org/legal/epl-v10.html";revision "2013-07-09" {description "";}// Augmentation nameextension "augment-identifier" {description"YANG language extension which assigns an identifier to augmentation.Augment identifier is used to identify specific augment statementby name. The identifier syntax is defined formally defined bythe rule 'identifier' in Section 12 of RFC 6020. All augment identifiersdefined in a namespace MUST be unique. The namespace of augmentidentifiers is shared by module and its submodules.";/*Discussion:This extension allows for ease of development / debugof YANG modules and it is suitable for code generation,where each augment statement is nicely identified byunique name instead of combination of augment targetand when condition.*/argument "identifier";}// Context-aware RPCsgrouping 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) schemanode as referencable context for RPCs. The argument is identitywhich 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";} }foo文件夾
這里面的文件都來自于opendaylight提供的源碼中拷貝出來
foo.xml
<?xml version="1.0" encoding="UTF-8"?><parent-container xmlns="foo-namespace"><leaf-container><union-identityref-leaf xmlns:prefix="foo-namespace">prefix:ident-one</union-identityref-leaf><int32-leaf>1500</int32-leaf><decimal64-leaf>150.45</decimal64-leaf><string-leaf>hello world</string-leaf><leafref-leaf>hello world</leafref-leaf><empty-leaf/><boolean-leaf>true</boolean-leaf><enum-leaf>five</enum-leaf></leaf-container><anyxml-container><my-anyxml><my-element><my-sub-element>< & sub-element value</my-sub-element></my-element></my-anyxml></anyxml-container> </parent-container>foo.yang
module foo {namespace "foo-namespace";prefix "f";identity ident-base;identity ident-one {base ident-base;}typedef union-type {type union {type uint8;type identityref {base ident-base;}}}container parent-container {container leaf-container {leaf union-identityref-leaf {type union-type;}leaf int32-leaf {type int32;}leaf decimal64-leaf {type decimal64 {fraction-digits 2;}}leaf string-leaf {type string;}leaf leafref-leaf {type leafref {path "../string-leaf";}}leaf empty-leaf {type empty;}leaf boolean-leaf {type boolean;}leaf enum-leaf {type enumeration {enum zero;enum one;enum five {value 5;}}}}container anyxml-container {anyxml my-anyxml;}}}第三步運行
?
?
可以發現生成的文件,可以手動對比一下原來的json和xml文件。
?
?
總結
以上是生活随笔為你收集整理的将NetConf转成NormalizedNode对象及NormalizedNode对象转回NetConf(序列化与反序列化)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 仿真环境Mininet的搭建
- 下一篇: java设计模式之【策略模式】