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.parsers.ParserConfigurationException;
27 import javax.xml.stream.XMLStreamException;
28 import javax.xml.transform.dom.DOMSource;
29 import org.opendaylight.controller.sal.rest.impl.test.providers.TestJsonBodyWriter;
30 import org.opendaylight.mdsal.dom.api.DOMMountPoint;
31 import org.opendaylight.mdsal.dom.api.DOMMountPointService;
32 import org.opendaylight.mdsal.dom.api.DOMSchemaService;
33 import org.opendaylight.mdsal.dom.spi.FixedDOMSchemaService;
34 import org.opendaylight.netconf.sal.restconf.impl.ControllerContext;
35 import org.opendaylight.restconf.common.context.InstanceIdentifierContext;
36 import org.opendaylight.restconf.common.context.NormalizedNodeContext;
37 import org.opendaylight.yangtools.util.xml.UntrustedXML;
38 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
39 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
40 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
41 import org.opendaylight.yangtools.yang.data.codec.xml.XmlParserStream;
42 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNormalizedNodeStreamWriter;
43 import org.opendaylight.yangtools.yang.data.impl.schema.NormalizedNodeResult;
44 import org.opendaylight.yangtools.yang.model.api.ContainerLike;
45 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
46 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
47 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
48 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
49 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
50 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
51 import org.opendaylight.yangtools.yang.model.util.SchemaInferenceStack;
52 import org.opendaylight.yangtools.yang.test.util.YangParserTestUtils;
53 import org.slf4j.Logger;
54 import org.slf4j.LoggerFactory;
55 import org.w3c.dom.Document;
56 import org.xml.sax.SAXException;
58 public final class TestRestconfUtils {
60 private static final Logger LOG = LoggerFactory.getLogger(TestRestconfUtils.class);
62 private TestRestconfUtils() {
63 throw new UnsupportedOperationException("Test utility class");
66 public static ControllerContext newControllerContext(final EffectiveModelContext schemaContext) {
67 return newControllerContext(schemaContext, null);
70 public static ControllerContext newControllerContext(final EffectiveModelContext schemaContext,
71 final DOMMountPoint mountInstance) {
72 final DOMMountPointService mockMountService = mock(DOMMountPointService.class);
74 if (mountInstance != null) {
75 doReturn(Optional.of(FixedDOMSchemaService.of(() -> schemaContext))).when(mountInstance)
76 .getService(eq(DOMSchemaService.class));
77 doReturn(Optional.ofNullable(mountInstance)).when(mockMountService).getMountPoint(
78 any(YangInstanceIdentifier.class));
81 DOMSchemaService mockSchemaService = mock(DOMSchemaService.class);
82 doReturn(schemaContext).when(mockSchemaService).getGlobalContext();
84 DOMSchemaService mockDomSchemaService = mock(DOMSchemaService.class);
85 doReturn(ImmutableClassToInstanceMap.of()).when(mockDomSchemaService).getExtensions();
87 return ControllerContext.newInstance(mockSchemaService, mockMountService, mockDomSchemaService);
90 @SuppressWarnings("checkstyle:IllegalCatch")
91 public static EffectiveModelContext loadSchemaContext(final String yangPath,
92 final EffectiveModelContext schemaContext) {
94 Preconditions.checkArgument(yangPath != null, "Path can not be null.");
95 Preconditions.checkArgument(!yangPath.isEmpty(), "Path can not be empty.");
96 if (schemaContext == null) {
97 return YangParserTestUtils.parseYangFiles(TestRestconfUtils.loadFiles(yangPath));
99 throw new UnsupportedOperationException("Unable to add new yang sources to existing schema context.");
101 } catch (final Exception e) {
102 LOG.error("Yang files at path: " + yangPath + " weren't loaded.", e);
104 return schemaContext;
107 public static NormalizedNodeContext loadNormalizedContextFromJsonFile() {
108 throw new AbstractMethodError("Not implemented yet");
111 @SuppressWarnings("checkstyle:IllegalCatch")
112 public static NormalizedNodeContext loadNormalizedContextFromXmlFile(final String pathToInputFile,
113 final String uri, final ControllerContext controllerContext) {
114 final InstanceIdentifierContext<?> iiContext = controllerContext.toInstanceIdentifier(uri);
115 final InputStream inputStream = TestJsonBodyWriter.class.getResourceAsStream(pathToInputFile);
117 final Document doc = UntrustedXML.newDocumentBuilder().parse(inputStream);
118 final NormalizedNode nn = parse(iiContext, doc);
119 return new NormalizedNodeContext(iiContext, nn);
120 } catch (final Exception e) {
121 LOG.error("Load xml file " + pathToInputFile + " fail.", e);
126 private static NormalizedNode parse(final InstanceIdentifierContext<?> iiContext, final Document doc)
127 throws XMLStreamException, IOException, ParserConfigurationException, SAXException, URISyntaxException {
128 final SchemaNode schemaNodeContext = iiContext.getSchemaNode();
129 DataSchemaNode schemaNode = null;
130 if (schemaNodeContext instanceof RpcDefinition) {
131 if ("input".equalsIgnoreCase(doc.getDocumentElement().getLocalName())) {
132 schemaNode = ((RpcDefinition) schemaNodeContext).getInput();
133 } else if ("output".equalsIgnoreCase(doc.getDocumentElement().getLocalName())) {
134 schemaNode = ((RpcDefinition) schemaNodeContext).getOutput();
136 throw new IllegalStateException("Unknown Rpc input node");
139 } else if (schemaNodeContext instanceof DataSchemaNode) {
140 schemaNode = (DataSchemaNode) schemaNodeContext;
142 throw new IllegalStateException("Unknow SchemaNode");
145 final String docRootElm = doc.getDocumentElement().getLocalName();
146 final String schemaNodeName = iiContext.getSchemaNode().getQName().getLocalName();
148 if (!schemaNodeName.equalsIgnoreCase(docRootElm)) {
149 for (final DataSchemaNode child : ((DataNodeContainer) schemaNode).getChildNodes()) {
150 if (child.getQName().getLocalName().equalsIgnoreCase(docRootElm)) {
157 final NormalizedNodeResult resultHolder = new NormalizedNodeResult();
158 final NormalizedNodeStreamWriter writer = ImmutableNormalizedNodeStreamWriter.from(resultHolder);
159 final XmlParserStream xmlParser = XmlParserStream.create(writer, SchemaInferenceStack.ofInstantiatedPath(
160 iiContext.getSchemaContext(), schemaNode.getPath()).toInference());
162 if (schemaNode instanceof ContainerLike || schemaNode instanceof ListSchemaNode) {
163 xmlParser.traverse(new DOMSource(doc.getDocumentElement()));
164 return resultHolder.getResult();
166 // FIXME : add another DataSchemaNode extensions e.g. LeafSchemaNode
170 public static Collection<File> loadFiles(final String resourceDirectory) throws FileNotFoundException {
171 final String path = TestRestconfUtils.class.getResource(resourceDirectory).getPath();
172 final File testDir = new File(path);
173 final String[] fileList = testDir.list();
174 final List<File> testFiles = new ArrayList<>();
175 if (fileList == null) {
176 throw new FileNotFoundException(resourceDirectory);
178 for (final String fileName : fileList) {
179 if (new File(testDir, fileName).isDirectory() == false) {
180 testFiles.add(new File(testDir, fileName));