Bump upstreams to SNAPSHOTs
[netconf.git] / restconf / restconf-nb-rfc8040 / src / test / java / org / opendaylight / restconf / nb / rfc8040 / 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 package org.opendaylight.restconf.nb.rfc8040;
9
10 import com.google.common.base.Preconditions;
11 import java.io.File;
12 import java.io.FileNotFoundException;
13 import java.io.IOException;
14 import java.io.InputStream;
15 import java.net.URISyntaxException;
16 import java.util.ArrayList;
17 import java.util.List;
18 import java.util.Optional;
19 import javax.xml.parsers.ParserConfigurationException;
20 import javax.xml.stream.XMLStreamException;
21 import javax.xml.transform.dom.DOMSource;
22 import org.opendaylight.restconf.common.context.InstanceIdentifierContext;
23 import org.opendaylight.restconf.nb.rfc8040.legacy.NormalizedNodePayload;
24 import org.opendaylight.restconf.nb.rfc8040.utils.parser.ParserIdentifier;
25 import org.opendaylight.yangtools.util.xml.UntrustedXML;
26 import org.opendaylight.yangtools.yang.common.YangConstants;
27 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
28 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
29 import org.opendaylight.yangtools.yang.data.codec.xml.XmlParserStream;
30 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNormalizedNodeStreamWriter;
31 import org.opendaylight.yangtools.yang.data.impl.schema.NormalizedNodeResult;
32 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
33 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
34 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
35 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
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.SchemaNode;
39 import org.opendaylight.yangtools.yang.test.util.YangParserTestUtils;
40 import org.slf4j.Logger;
41 import org.slf4j.LoggerFactory;
42 import org.w3c.dom.Document;
43 import org.xml.sax.SAXException;
44
45 public final class TestRestconfUtils {
46
47     private static final Logger LOG = LoggerFactory.getLogger(TestRestconfUtils.class);
48
49     private TestRestconfUtils() {
50         throw new UnsupportedOperationException("Test utility class");
51     }
52
53     @SuppressWarnings("checkstyle:IllegalCatch")
54     public static EffectiveModelContext loadSchemaContext(final String yangPath,
55             final EffectiveModelContext 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.parseYangFiles(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.", e);
66         }
67         return schemaContext;
68     }
69
70     @SuppressWarnings("checkstyle:IllegalCatch")
71     public static NormalizedNodePayload loadNormalizedContextFromXmlFile(final String pathToInputFile,
72             final String uri, final EffectiveModelContext schemaContext) {
73         final InstanceIdentifierContext iiContext =
74                 ParserIdentifier.toInstanceIdentifier(uri, schemaContext, Optional.empty());
75         final InputStream inputStream = TestRestconfUtils.class.getResourceAsStream(pathToInputFile);
76         try {
77             final Document doc = UntrustedXML.newDocumentBuilder().parse(inputStream);
78             final NormalizedNode nn = parse(iiContext, doc);
79             return NormalizedNodePayload.of(iiContext, nn);
80         } catch (final Exception e) {
81             LOG.error("Load xml file {} fail.", pathToInputFile, e);
82         }
83         return null;
84     }
85
86     private static NormalizedNode parse(final InstanceIdentifierContext iiContext, final Document doc)
87             throws XMLStreamException, IOException, ParserConfigurationException, SAXException, URISyntaxException {
88         final SchemaNode schemaNodeContext = iiContext.getSchemaNode();
89         DataSchemaNode schemaNode = null;
90         if (schemaNodeContext instanceof RpcDefinition) {
91             if ("input".equalsIgnoreCase(doc.getDocumentElement().getLocalName())) {
92                 schemaNode = ((RpcDefinition) schemaNodeContext).getInput();
93             } else if ("output".equalsIgnoreCase(doc.getDocumentElement().getLocalName())) {
94                 schemaNode = ((RpcDefinition) schemaNodeContext).getOutput();
95             } else {
96                 throw new IllegalStateException("Unknown Rpc input node");
97             }
98
99         } else if (schemaNodeContext instanceof DataSchemaNode) {
100             schemaNode = (DataSchemaNode) schemaNodeContext;
101         } else {
102             throw new IllegalStateException("Unknow SchemaNode");
103         }
104
105         final String docRootElm = doc.getDocumentElement().getLocalName();
106         final String schemaNodeName = iiContext.getSchemaNode().getQName().getLocalName();
107
108         if (!schemaNodeName.equalsIgnoreCase(docRootElm)) {
109             for (final DataSchemaNode child : ((DataNodeContainer) schemaNode).getChildNodes()) {
110                 if (child.getQName().getLocalName().equalsIgnoreCase(docRootElm)) {
111                     schemaNode = child;
112                     break;
113                 }
114             }
115         }
116
117         final NormalizedNodeResult resultHolder = new NormalizedNodeResult();
118         final NormalizedNodeStreamWriter writer = ImmutableNormalizedNodeStreamWriter.from(resultHolder);
119         final XmlParserStream xmlParser = XmlParserStream.create(writer, iiContext.inference());
120
121         if (schemaNode instanceof ContainerSchemaNode || schemaNode instanceof ListSchemaNode) {
122             xmlParser.traverse(new DOMSource(doc.getDocumentElement()));
123             return resultHolder.getResult();
124         }
125         // FIXME : add another DataSchemaNode extensions e.g. LeafSchemaNode
126         return null;
127     }
128
129     public static List<File> loadFiles(final String resourceDirectory) throws FileNotFoundException {
130         final String path = TestRestconfUtils.class.getResource(resourceDirectory).getPath();
131         final File testDir = new File(path);
132         final String[] fileList = testDir.list();
133         final List<File> testFiles = new ArrayList<>();
134         if (fileList == null) {
135             throw new FileNotFoundException(resourceDirectory);
136         }
137         for (final String fileName : fileList) {
138             if (fileName.endsWith(YangConstants.RFC6020_YANG_FILE_EXTENSION)
139                 && !new File(testDir, fileName).isDirectory()) {
140                 testFiles.add(new File(testDir, fileName));
141             }
142         }
143         return testFiles;
144     }
145 }