39d4292d1806e6356311ac68425cb8fb5c6b80f1
[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.Collection;
18 import java.util.List;
19 import java.util.Optional;
20 import javax.xml.parsers.ParserConfigurationException;
21 import javax.xml.stream.XMLStreamException;
22 import javax.xml.transform.dom.DOMSource;
23 import org.opendaylight.restconf.common.context.InstanceIdentifierContext;
24 import org.opendaylight.restconf.common.context.NormalizedNodeContext;
25 import org.opendaylight.restconf.nb.rfc8040.utils.parser.ParserIdentifier;
26 import org.opendaylight.yangtools.util.xml.UntrustedXML;
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.model.util.SchemaInferenceStack;
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 final 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 EffectiveModelContext loadSchemaContext(final String yangPath,
56             final EffectiveModelContext schemaContext) {
57         try {
58             Preconditions.checkArgument(yangPath != null, "Path can not be null.");
59             Preconditions.checkArgument(!yangPath.isEmpty(), "Path can not be empty.");
60             if (schemaContext == null) {
61                 return YangParserTestUtils.parseYangFiles(TestRestconfUtils.loadFiles(yangPath));
62             } else {
63                 throw new UnsupportedOperationException("Unable to add new yang sources to existing schema context.");
64             }
65         } catch (final Exception e) {
66             LOG.error("Yang files at path: " + yangPath + " weren't loaded.", e);
67         }
68         return schemaContext;
69     }
70
71     public static NormalizedNodeContext loadNormalizedContextFromJsonFile() {
72         throw new AbstractMethodError("Not implemented yet");
73     }
74
75     @SuppressWarnings("checkstyle:IllegalCatch")
76     public static NormalizedNodeContext loadNormalizedContextFromXmlFile(final String pathToInputFile,
77             final String uri, final EffectiveModelContext schemaContext) {
78         final InstanceIdentifierContext<?> iiContext =
79                 ParserIdentifier.toInstanceIdentifier(uri, schemaContext, Optional.empty());
80         final InputStream inputStream = TestRestconfUtils.class.getResourceAsStream(pathToInputFile);
81         try {
82             final Document doc = UntrustedXML.newDocumentBuilder().parse(inputStream);
83             final NormalizedNode nn = parse(iiContext, doc);
84             return new NormalizedNodeContext(iiContext, nn);
85         } catch (final Exception e) {
86             LOG.error("Load xml file " + pathToInputFile + " fail.", e);
87         }
88         return null;
89     }
90
91     private static NormalizedNode parse(final InstanceIdentifierContext<?> iiContext, final Document doc)
92             throws XMLStreamException, IOException, ParserConfigurationException, SAXException, URISyntaxException {
93         final SchemaNode schemaNodeContext = iiContext.getSchemaNode();
94         DataSchemaNode schemaNode = null;
95         if (schemaNodeContext instanceof RpcDefinition) {
96             if ("input".equalsIgnoreCase(doc.getDocumentElement().getLocalName())) {
97                 schemaNode = ((RpcDefinition) schemaNodeContext).getInput();
98             } else if ("output".equalsIgnoreCase(doc.getDocumentElement().getLocalName())) {
99                 schemaNode = ((RpcDefinition) schemaNodeContext).getOutput();
100             } else {
101                 throw new IllegalStateException("Unknown Rpc input node");
102             }
103
104         } else if (schemaNodeContext instanceof DataSchemaNode) {
105             schemaNode = (DataSchemaNode) schemaNodeContext;
106         } else {
107             throw new IllegalStateException("Unknow SchemaNode");
108         }
109
110         final String docRootElm = doc.getDocumentElement().getLocalName();
111         final String schemaNodeName = iiContext.getSchemaNode().getQName().getLocalName();
112
113         if (!schemaNodeName.equalsIgnoreCase(docRootElm)) {
114             for (final DataSchemaNode child : ((DataNodeContainer) schemaNode).getChildNodes()) {
115                 if (child.getQName().getLocalName().equalsIgnoreCase(docRootElm)) {
116                     schemaNode = child;
117                     break;
118                 }
119             }
120         }
121
122         final NormalizedNodeResult resultHolder = new NormalizedNodeResult();
123         final NormalizedNodeStreamWriter writer = ImmutableNormalizedNodeStreamWriter.from(resultHolder);
124         final XmlParserStream xmlParser = XmlParserStream.create(writer,
125             SchemaInferenceStack.ofInstantiatedPath(iiContext.getSchemaContext(), schemaNode.getPath()).toInference());
126
127         if (schemaNode instanceof ContainerSchemaNode || schemaNode instanceof ListSchemaNode) {
128             xmlParser.traverse(new DOMSource(doc.getDocumentElement()));
129             return resultHolder.getResult();
130         }
131         // FIXME : add another DataSchemaNode extensions e.g. LeafSchemaNode
132         return null;
133     }
134
135     public static Collection<File> loadFiles(final String resourceDirectory) throws FileNotFoundException {
136         final String path = TestRestconfUtils.class.getResource(resourceDirectory).getPath();
137         final File testDir = new File(path);
138         final String[] fileList = testDir.list();
139         final List<File> testFiles = new ArrayList<>();
140         if (fileList == null) {
141             throw new FileNotFoundException(resourceDirectory);
142         }
143         for (final String fileName : fileList) {
144             if (new File(testDir, fileName).isDirectory() == false) {
145                 testFiles.add(new File(testDir, fileName));
146             }
147         }
148         return testFiles;
149     }
150 }