Split Restconf implementations (draft02 and RFC) - Prepare modules
[netconf.git] / restconf / restconf-nb-bierman02 / 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 com.google.common.base.Preconditions;
12 import java.io.File;
13 import java.io.FileNotFoundException;
14 import java.io.IOException;
15 import java.io.InputStream;
16 import java.net.URISyntaxException;
17 import java.util.ArrayList;
18 import java.util.Collection;
19 import java.util.List;
20 import javax.xml.parsers.ParserConfigurationException;
21 import javax.xml.stream.XMLStreamException;
22 import javax.xml.transform.dom.DOMSource;
23 import org.opendaylight.controller.sal.rest.impl.test.providers.TestJsonBodyWriter;
24 import org.opendaylight.netconf.sal.restconf.impl.ControllerContext;
25 import org.opendaylight.netconf.sal.restconf.impl.InstanceIdentifierContext;
26 import org.opendaylight.netconf.sal.restconf.impl.NormalizedNodeContext;
27 import org.opendaylight.yangtools.util.xml.UntrustedXML;
28 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
29 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
30 import org.opendaylight.yangtools.yang.data.codec.xml.XmlParserStream;
31 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNormalizedNodeStreamWriter;
32 import org.opendaylight.yangtools.yang.data.impl.schema.NormalizedNodeResult;
33 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
34 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
35 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
36 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
37 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
38 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
39 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
40 import org.opendaylight.yangtools.yang.test.util.YangParserTestUtils;
41 import org.slf4j.Logger;
42 import org.slf4j.LoggerFactory;
43 import org.w3c.dom.Document;
44 import org.xml.sax.SAXException;
45
46 public class TestRestconfUtils {
47
48     private static final Logger LOG = LoggerFactory.getLogger(TestRestconfUtils.class);
49
50     private TestRestconfUtils() {
51         throw new UnsupportedOperationException("Test utility class");
52     }
53
54     @SuppressWarnings("checkstyle:IllegalCatch")
55     public static SchemaContext loadSchemaContext(final String yangPath, final SchemaContext schemaContext) {
56         try {
57             Preconditions.checkArgument(yangPath != null, "Path can not be null.");
58             Preconditions.checkArgument((!yangPath.isEmpty()), "Path can not be empty.");
59             if (schemaContext == null) {
60                 return YangParserTestUtils.parseYangSources(TestRestconfUtils.loadFiles(yangPath));
61             } else {
62                 throw new UnsupportedOperationException("Unable to add new yang sources to existing schema context.");
63             }
64         } catch (final Exception e) {
65             LOG.error("Yang files at path: " + yangPath + " weren't loaded.");
66         }
67         return schemaContext;
68     }
69
70     public static NormalizedNodeContext loadNormalizedContextFromJsonFile() {
71         throw new AbstractMethodError("Not implemented yet");
72     }
73
74     @SuppressWarnings("checkstyle:IllegalCatch")
75     public static NormalizedNodeContext loadNormalizedContextFromXmlFile(final String pathToInputFile,
76             final String uri) {
77         final InstanceIdentifierContext<?> iiContext = ControllerContext.getInstance().toInstanceIdentifier(uri);
78         final InputStream inputStream = TestJsonBodyWriter.class.getResourceAsStream(pathToInputFile);
79         try {
80             final Document doc = UntrustedXML.newDocumentBuilder().parse(inputStream);
81             final NormalizedNode<?, ?> nn = parse(iiContext, doc);
82             return new NormalizedNodeContext(iiContext, nn);
83         } catch (final Exception e) {
84             LOG.error("Load xml file " + pathToInputFile + " fail.", e);
85         }
86         return null;
87     }
88
89     private static NormalizedNode<?, ?> parse(final InstanceIdentifierContext<?> iiContext, final Document doc)
90             throws XMLStreamException, IOException, ParserConfigurationException, SAXException, URISyntaxException {
91         final SchemaNode schemaNodeContext = iiContext.getSchemaNode();
92         DataSchemaNode schemaNode = null;
93         if (schemaNodeContext instanceof RpcDefinition) {
94             if ("input".equalsIgnoreCase(doc.getDocumentElement().getLocalName())) {
95                 schemaNode = ((RpcDefinition) schemaNodeContext).getInput();
96             } else if ("output".equalsIgnoreCase(doc.getDocumentElement().getLocalName())) {
97                 schemaNode = ((RpcDefinition) schemaNodeContext).getOutput();
98             } else {
99                 throw new IllegalStateException("Unknown Rpc input node");
100             }
101
102         } else if (schemaNodeContext instanceof DataSchemaNode) {
103             schemaNode = (DataSchemaNode) schemaNodeContext;
104         } else {
105             throw new IllegalStateException("Unknow SchemaNode");
106         }
107
108         final String docRootElm = doc.getDocumentElement().getLocalName();
109         final String schemaNodeName = iiContext.getSchemaNode().getQName().getLocalName();
110
111         if (!schemaNodeName.equalsIgnoreCase(docRootElm)) {
112             final Collection<DataSchemaNode> children = ((DataNodeContainer) schemaNode).getChildNodes();
113             for (final DataSchemaNode child : children) {
114                 if (child.getQName().getLocalName().equalsIgnoreCase(docRootElm)) {
115                     schemaNode = child;
116                     break;
117                 }
118             }
119         }
120
121         final NormalizedNodeResult resultHolder = new NormalizedNodeResult();
122         final NormalizedNodeStreamWriter writer = ImmutableNormalizedNodeStreamWriter.from(resultHolder);
123         final XmlParserStream xmlParser = XmlParserStream.create(writer, iiContext.getSchemaContext(), schemaNode);
124
125         if (schemaNode instanceof ContainerSchemaNode || schemaNode instanceof ListSchemaNode) {
126             xmlParser.traverse(new DOMSource(doc.getDocumentElement()));
127             return resultHolder.getResult();
128         }
129         // FIXME : add another DataSchemaNode extensions e.g. LeafSchemaNode
130         return null;
131     }
132
133     public static Collection<File> loadFiles(final String resourceDirectory) throws FileNotFoundException {
134         final String path = TestRestconfUtils.class.getResource(resourceDirectory).getPath();
135         final File testDir = new File(path);
136         final String[] fileList = testDir.list();
137         final List<File> testFiles = new ArrayList<>();
138         if (fileList == null) {
139             throw new FileNotFoundException(resourceDirectory);
140         }
141         for (final String fileName : fileList) {
142             if (new File(testDir, fileName).isDirectory() == false) {
143                 testFiles.add(new File(testDir, fileName));
144             }
145         }
146         return testFiles;
147     }
148 }