9dea0b95cd0a517b45f5ad50a6a11c4a9b0769e8
[netconf.git] / opendaylight / restconf / sal-rest-connector / src / test / java / org / opendaylight / controller / md / sal / rest / common / TestRestconfUtils.java
1 /**
2  * Copyright (c) 2015 Cisco Systems, Inc. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8
9 package org.opendaylight.controller.md.sal.rest.common;
10
11 import java.io.File;
12 import java.io.FileNotFoundException;
13 import java.io.InputStream;
14 import java.net.URISyntaxException;
15 import java.util.ArrayList;
16 import java.util.Collection;
17 import java.util.Collections;
18 import java.util.List;
19
20 import javax.xml.parsers.DocumentBuilder;
21 import javax.xml.parsers.DocumentBuilderFactory;
22 import javax.xml.parsers.ParserConfigurationException;
23
24 import org.opendaylight.controller.sal.rest.impl.test.providers.TestJsonBodyWriter;
25 import org.opendaylight.netconf.sal.restconf.impl.ControllerContext;
26 import org.opendaylight.netconf.sal.restconf.impl.InstanceIdentifierContext;
27 import org.opendaylight.netconf.sal.restconf.impl.NormalizedNodeContext;
28 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
29 import org.opendaylight.yangtools.yang.data.impl.codec.xml.XmlUtils;
30 import org.opendaylight.yangtools.yang.data.impl.schema.transform.dom.parser.DomToNormalizedNodeParserFactory;
31 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
32 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
33 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
34 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
35 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
36 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
37 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
38 import org.opendaylight.yangtools.yang.parser.spi.meta.ReactorException;
39 import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
40 import org.opendaylight.yangtools.yang.parser.stmt.reactor.CrossSourceStatementReactor;
41 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.YangInferencePipeline;
42 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.YangStatementSourceImpl;
43 import org.opendaylight.yangtools.yang.parser.util.NamedFileInputStream;
44 import org.slf4j.Logger;
45 import org.slf4j.LoggerFactory;
46 import org.w3c.dom.Document;
47 import org.w3c.dom.Element;
48
49 import com.google.common.base.Preconditions;
50
51 /**
52  * sal-rest-connector
53  * org.opendaylight.controller.md.sal.rest.common
54  *
55  *
56  *
57  * @author <a href="mailto:vdemcak@cisco.com">Vaclav Demcak</a>
58  *
59  * Created: Mar 7, 2015
60  */
61 public class TestRestconfUtils {
62
63     private static final Logger LOG = LoggerFactory.getLogger(TestRestconfUtils.class);
64
65     private static final DocumentBuilderFactory BUILDERFACTORY;
66
67     static {
68         final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
69         try {
70             factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
71             factory.setFeature("http://xml.org/sax/features/external-general-entities", false);
72             factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
73             factory.setXIncludeAware(false);
74             factory.setExpandEntityReferences(false);
75         } catch (final ParserConfigurationException e) {
76             throw new ExceptionInInitializerError(e);
77         }
78         factory.setNamespaceAware(true);
79         factory.setCoalescing(true);
80         factory.setIgnoringElementContentWhitespace(true);
81         factory.setIgnoringComments(true);
82         BUILDERFACTORY = factory;
83     }
84
85     private TestRestconfUtils () {
86         throw new UnsupportedOperationException("Test utility class");
87     }
88
89     public static SchemaContext loadSchemaContext(final String yangPath, final SchemaContext schemaContext) {
90         try {
91             Preconditions.checkArgument(yangPath != null, "Path can not be null.");
92             Preconditions.checkArgument(( ! yangPath.isEmpty()), "Path can not be empty.");
93             if (schemaContext == null) {
94                 return loadSchemaContext(yangPath);
95             } else {
96                 throw new UnsupportedOperationException("Unable to add new yang sources to existing schema context.");
97             }
98         }
99         catch (final Exception e) {
100             LOG.error("Yang files at path: " + yangPath + " weren't loaded.");
101         }
102         return schemaContext;
103     }
104
105     public static NormalizedNodeContext loadNormalizedContextFromJsonFile() {
106         throw new AbstractMethodError("Not implemented yet");
107     }
108
109     public static NormalizedNodeContext loadNormalizedContextFromXmlFile(final String pathToInputFile, final String uri) {
110         final InstanceIdentifierContext<?> iiContext = ControllerContext.getInstance().toInstanceIdentifier(uri);
111         final InputStream inputStream = TestJsonBodyWriter.class.getResourceAsStream(pathToInputFile);
112         try {
113             final DocumentBuilder dBuilder = BUILDERFACTORY.newDocumentBuilder();
114             final Document doc = dBuilder.parse(inputStream);
115             final NormalizedNode<?, ?> nn = parse(iiContext, doc);
116             return new NormalizedNodeContext(iiContext, nn);
117         }
118         catch (final Exception e) {
119             LOG.error("Load xml file " + pathToInputFile + " fail.", e);
120         }
121         return null;
122     }
123
124     private static NormalizedNode<?, ?> parse(final InstanceIdentifierContext<?> iiContext, final Document doc) {
125         final List<Element> elements = Collections.singletonList(doc.getDocumentElement());
126         final SchemaNode schemaNodeContext = iiContext.getSchemaNode();
127         DataSchemaNode schemaNode = null;
128         if (schemaNodeContext instanceof RpcDefinition) {
129             if ("input".equalsIgnoreCase(doc.getDocumentElement().getLocalName())) {
130                 schemaNode = ((RpcDefinition) schemaNodeContext).getInput();
131             } else if ("output".equalsIgnoreCase(doc.getDocumentElement().getLocalName())) {
132                 schemaNode = ((RpcDefinition) schemaNodeContext).getOutput();
133             } else {
134                 throw new IllegalStateException("Unknown Rpc input node");
135             }
136
137         } else if (schemaNodeContext instanceof DataSchemaNode) {
138             schemaNode = (DataSchemaNode) schemaNodeContext;
139         } else {
140             throw new IllegalStateException("Unknow SchemaNode");
141         }
142
143         final String docRootElm = doc.getDocumentElement().getLocalName();
144         final String schemaNodeName = iiContext.getSchemaNode().getQName().getLocalName();
145
146         if (!schemaNodeName.equalsIgnoreCase(docRootElm)) {
147             final Collection<DataSchemaNode> children = ((DataNodeContainer) schemaNode).getChildNodes();
148             for (final DataSchemaNode child : children) {
149                 if (child.getQName().getLocalName().equalsIgnoreCase(docRootElm)) {
150                     schemaNode = child;
151                     break;
152                 }
153             }
154         }
155         final DomToNormalizedNodeParserFactory parserFactory =
156                 DomToNormalizedNodeParserFactory.getInstance(XmlUtils.DEFAULT_XML_CODEC_PROVIDER, iiContext.getSchemaContext());
157
158         if(schemaNode instanceof ContainerSchemaNode) {
159             return parserFactory.getContainerNodeParser().parse(Collections.singletonList(doc.getDocumentElement()), (ContainerSchemaNode) schemaNode);
160         } else if(schemaNode instanceof ListSchemaNode) {
161             final ListSchemaNode casted = (ListSchemaNode) schemaNode;
162             return parserFactory.getMapEntryNodeParser().parse(elements, casted);
163         } // FIXME : add another DataSchemaNode extensions e.g. LeafSchemaNode
164         return null;
165     }
166
167     public static Collection<File> loadFiles(final String resourceDirectory) throws FileNotFoundException {
168         final String path = TestRestconfUtils.class.getResource(resourceDirectory).getPath();
169         final File testDir = new File(path);
170         final String[] fileList = testDir.list();
171         final List<File> testFiles = new ArrayList<File>();
172         if (fileList == null) {
173             throw new FileNotFoundException(resourceDirectory);
174         }
175         for (int i = 0; i < fileList.length; i++) {
176             final String fileName = fileList[i];
177             if (new File(testDir, fileName).isDirectory() == false) {
178                 testFiles.add(new File(testDir, fileName));
179             }
180         }
181         return testFiles;
182     }
183
184     public static SchemaContext loadSchemaContext(String resourceDirectory)
185             throws SourceException, ReactorException, FileNotFoundException,
186             URISyntaxException {
187         return parseYangSources(loadFiles(resourceDirectory));
188     }
189
190     public static SchemaContext parseYangSources(Collection<File> testFiles)
191             throws SourceException, ReactorException, FileNotFoundException {
192         CrossSourceStatementReactor.BuildAction reactor = YangInferencePipeline.RFC6020_REACTOR
193                 .newBuild();
194         for (File testFile : testFiles) {
195             reactor.addSource(new YangStatementSourceImpl(
196                     new NamedFileInputStream(testFile, testFile.getPath())));
197         }
198
199         return reactor.buildEffective();
200     }
201 }