2 * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
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
8 package org.opendaylight.controller.md.sal.rest.common;
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;
15 import com.google.common.base.Preconditions;
16 import com.google.common.collect.ImmutableClassToInstanceMap;
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;
57 public final class TestRestconfUtils {
59 private static final Logger LOG = LoggerFactory.getLogger(TestRestconfUtils.class);
61 private TestRestconfUtils() {
62 throw new UnsupportedOperationException("Test utility class");
65 public static ControllerContext newControllerContext(final EffectiveModelContext schemaContext) {
66 return newControllerContext(schemaContext, null);
69 public static ControllerContext newControllerContext(final EffectiveModelContext schemaContext,
70 final DOMMountPoint mountInstance) {
71 final DOMMountPointService mockMountService = mock(DOMMountPointService.class);
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));
80 DOMSchemaService mockSchemaService = mock(DOMSchemaService.class);
81 doReturn(schemaContext).when(mockSchemaService).getGlobalContext();
83 DOMSchemaService mockDomSchemaService = mock(DOMSchemaService.class);
84 doReturn(ImmutableClassToInstanceMap.of()).when(mockDomSchemaService).getExtensions();
86 return ControllerContext.newInstance(mockSchemaService, mockMountService, mockDomSchemaService);
89 @SuppressWarnings("checkstyle:IllegalCatch")
90 public static EffectiveModelContext loadSchemaContext(final String yangPath,
91 final EffectiveModelContext schemaContext) {
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));
98 throw new UnsupportedOperationException("Unable to add new yang sources to existing schema context.");
100 } catch (final Exception e) {
101 LOG.error("Yang files at path: " + yangPath + " weren't loaded.", e);
103 return schemaContext;
106 public static NormalizedNodeContext loadNormalizedContextFromJsonFile() {
107 throw new AbstractMethodError("Not implemented yet");
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);
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);
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();
139 throw new IllegalStateException("Unknown Rpc input node");
141 stack.enterSchemaTree(schemaNode.getQName());
142 } else if (schemaNodeContext instanceof DataSchemaNode) {
143 schemaNode = (DataSchemaNode) schemaNodeContext;
144 stack = iiContext.inference().toSchemaInferenceStack();
146 throw new IllegalStateException("Unknow SchemaNode");
149 final String docRootElm = doc.getDocumentElement().getLocalName();
150 final String schemaNodeName = iiContext.getSchemaNode().getQName().getLocalName();
152 if (!schemaNodeName.equalsIgnoreCase(docRootElm)) {
153 for (final DataSchemaNode child : ((DataNodeContainer) schemaNode).getChildNodes()) {
154 if (child.getQName().getLocalName().equalsIgnoreCase(docRootElm)) {
156 stack.enterSchemaTree(child.getQName());
162 final NormalizedNodeResult resultHolder = new NormalizedNodeResult();
163 final NormalizedNodeStreamWriter writer = ImmutableNormalizedNodeStreamWriter.from(resultHolder);
164 final XmlParserStream xmlParser = XmlParserStream.create(writer, stack.toInference());
166 if (schemaNode instanceof ContainerLike || schemaNode instanceof ListSchemaNode) {
167 xmlParser.traverse(new DOMSource(doc.getDocumentElement()));
168 return resultHolder.getResult();
170 // FIXME : add another DataSchemaNode extensions e.g. LeafSchemaNode
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);
182 for (final String fileName : fileList) {
183 if (new File(testDir, fileName).isDirectory() == false) {
184 testFiles.add(new File(testDir, fileName));