d88379729a6547e39ea1f826753b4129e738f5ce
[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 package org.opendaylight.controller.md.sal.rest.common;
9
10 import static org.mockito.ArgumentMatchers.any;
11 import static org.mockito.ArgumentMatchers.eq;
12 import static org.mockito.Mockito.doReturn;
13 import static org.mockito.Mockito.mock;
14
15 import com.google.common.base.Preconditions;
16 import com.google.common.collect.ImmutableClassToInstanceMap;
17 import java.io.File;
18 import java.io.FileNotFoundException;
19 import java.io.IOException;
20 import java.io.InputStream;
21 import java.net.URISyntaxException;
22 import java.util.ArrayList;
23 import java.util.Collection;
24 import java.util.List;
25 import java.util.Optional;
26 import javax.xml.stream.XMLStreamException;
27 import javax.xml.transform.dom.DOMSource;
28 import org.opendaylight.controller.sal.rest.impl.test.providers.TestJsonBodyWriter;
29 import org.opendaylight.mdsal.dom.api.DOMMountPoint;
30 import org.opendaylight.mdsal.dom.api.DOMMountPointService;
31 import org.opendaylight.mdsal.dom.api.DOMSchemaService;
32 import org.opendaylight.mdsal.dom.spi.FixedDOMSchemaService;
33 import org.opendaylight.netconf.sal.rest.impl.NormalizedNodeContext;
34 import org.opendaylight.netconf.sal.restconf.impl.ControllerContext;
35 import org.opendaylight.restconf.common.context.InstanceIdentifierContext;
36 import org.opendaylight.yangtools.util.xml.UntrustedXML;
37 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
38 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
39 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
40 import org.opendaylight.yangtools.yang.data.codec.xml.XmlParserStream;
41 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNormalizedNodeStreamWriter;
42 import org.opendaylight.yangtools.yang.data.impl.schema.NormalizedNodeResult;
43 import org.opendaylight.yangtools.yang.model.api.ContainerLike;
44 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
45 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
46 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
47 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
48 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
49 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
50 import org.opendaylight.yangtools.yang.model.util.SchemaInferenceStack;
51 import org.opendaylight.yangtools.yang.test.util.YangParserTestUtils;
52 import org.slf4j.Logger;
53 import org.slf4j.LoggerFactory;
54 import org.w3c.dom.Document;
55 import org.xml.sax.SAXException;
56
57 public final class TestRestconfUtils {
58
59     private static final Logger LOG = LoggerFactory.getLogger(TestRestconfUtils.class);
60
61     private TestRestconfUtils() {
62         throw new UnsupportedOperationException("Test utility class");
63     }
64
65     public static ControllerContext newControllerContext(final EffectiveModelContext schemaContext) {
66         return newControllerContext(schemaContext, null);
67     }
68
69     public static ControllerContext newControllerContext(final EffectiveModelContext schemaContext,
70             final DOMMountPoint mountInstance) {
71         final DOMMountPointService mockMountService = mock(DOMMountPointService.class);
72
73         if (mountInstance != null) {
74             doReturn(Optional.of(FixedDOMSchemaService.of(() -> schemaContext))).when(mountInstance)
75                 .getService(eq(DOMSchemaService.class));
76             doReturn(Optional.ofNullable(mountInstance)).when(mockMountService).getMountPoint(
77                 any(YangInstanceIdentifier.class));
78         }
79
80         DOMSchemaService mockSchemaService = mock(DOMSchemaService.class);
81         doReturn(schemaContext).when(mockSchemaService).getGlobalContext();
82
83         DOMSchemaService mockDomSchemaService = mock(DOMSchemaService.class);
84         doReturn(ImmutableClassToInstanceMap.of()).when(mockDomSchemaService).getExtensions();
85
86         return ControllerContext.newInstance(mockSchemaService, mockMountService, mockDomSchemaService);
87     }
88
89     @SuppressWarnings("checkstyle:IllegalCatch")
90     public static EffectiveModelContext loadSchemaContext(final String yangPath,
91             final EffectiveModelContext schemaContext) {
92         try {
93             Preconditions.checkArgument(yangPath != null, "Path can not be null.");
94             Preconditions.checkArgument(!yangPath.isEmpty(), "Path can not be empty.");
95             if (schemaContext == null) {
96                 return YangParserTestUtils.parseYangFiles(TestRestconfUtils.loadFiles(yangPath));
97             } else {
98                 throw new UnsupportedOperationException("Unable to add new yang sources to existing schema context.");
99             }
100         } catch (final Exception e) {
101             LOG.error("Yang files at path: " + yangPath + " weren't loaded.", e);
102         }
103         return schemaContext;
104     }
105
106     public static NormalizedNodeContext loadNormalizedContextFromJsonFile() {
107         throw new AbstractMethodError("Not implemented yet");
108     }
109
110     @SuppressWarnings("checkstyle:IllegalCatch")
111     public static NormalizedNodeContext loadNormalizedContextFromXmlFile(final String pathToInputFile,
112             final String uri, final ControllerContext controllerContext) {
113         final InstanceIdentifierContext iiContext = controllerContext.toInstanceIdentifier(uri);
114         final InputStream inputStream = TestJsonBodyWriter.class.getResourceAsStream(pathToInputFile);
115         try {
116             final Document doc = UntrustedXML.newDocumentBuilder().parse(inputStream);
117             final NormalizedNode nn = parse(iiContext, doc);
118             return new NormalizedNodeContext(iiContext, nn);
119         } catch (final Exception e) {
120             LOG.error("Load xml file " + pathToInputFile + " fail.", e);
121         }
122         return null;
123     }
124
125     private static NormalizedNode parse(final InstanceIdentifierContext iiContext, final Document doc)
126             throws XMLStreamException, IOException, SAXException, URISyntaxException {
127         final SchemaNode schemaNodeContext = iiContext.getSchemaNode();
128         final SchemaInferenceStack stack;
129         DataSchemaNode schemaNode = null;
130         if (schemaNodeContext instanceof RpcDefinition) {
131             final var rpc = (RpcDefinition) schemaNodeContext;
132             stack = SchemaInferenceStack.of(iiContext.getSchemaContext());
133             stack.enterSchemaTree(rpc.getQName());
134             if ("input".equalsIgnoreCase(doc.getDocumentElement().getLocalName())) {
135                 schemaNode = rpc.getInput();
136             } else if ("output".equalsIgnoreCase(doc.getDocumentElement().getLocalName())) {
137                 schemaNode = rpc.getOutput();
138             } else {
139                 throw new IllegalStateException("Unknown Rpc input node");
140             }
141             stack.enterSchemaTree(schemaNode.getQName());
142         } else if (schemaNodeContext instanceof DataSchemaNode) {
143             schemaNode = (DataSchemaNode) schemaNodeContext;
144             stack = iiContext.inference().toSchemaInferenceStack();
145         } else {
146             throw new IllegalStateException("Unknow SchemaNode");
147         }
148
149         final String docRootElm = doc.getDocumentElement().getLocalName();
150         final String schemaNodeName = iiContext.getSchemaNode().getQName().getLocalName();
151
152         if (!schemaNodeName.equalsIgnoreCase(docRootElm)) {
153             for (final DataSchemaNode child : ((DataNodeContainer) schemaNode).getChildNodes()) {
154                 if (child.getQName().getLocalName().equalsIgnoreCase(docRootElm)) {
155                     schemaNode = child;
156                     stack.enterSchemaTree(child.getQName());
157                     break;
158                 }
159             }
160         }
161
162         final NormalizedNodeResult resultHolder = new NormalizedNodeResult();
163         final NormalizedNodeStreamWriter writer = ImmutableNormalizedNodeStreamWriter.from(resultHolder);
164         final XmlParserStream xmlParser = XmlParserStream.create(writer, stack.toInference());
165
166         if (schemaNode instanceof ContainerLike || schemaNode instanceof ListSchemaNode) {
167             xmlParser.traverse(new DOMSource(doc.getDocumentElement()));
168             return resultHolder.getResult();
169         }
170         // FIXME : add another DataSchemaNode extensions e.g. LeafSchemaNode
171         return null;
172     }
173
174     public static Collection<File> loadFiles(final String resourceDirectory) throws FileNotFoundException {
175         final String path = TestRestconfUtils.class.getResource(resourceDirectory).getPath();
176         final File testDir = new File(path);
177         final String[] fileList = testDir.list();
178         final List<File> testFiles = new ArrayList<>();
179         if (fileList == null) {
180             throw new FileNotFoundException(resourceDirectory);
181         }
182         for (final String fileName : fileList) {
183             if (new File(testDir, fileName).isDirectory() == false) {
184                 testFiles.add(new File(testDir, fileName));
185             }
186         }
187         return testFiles;
188     }
189 }