Update MRI projects for Aluminium
[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.Mockito.doCallRealMethod;
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.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.netconf.sal.restconf.impl.ControllerContext;
34 import org.opendaylight.restconf.common.context.InstanceIdentifierContext;
35 import org.opendaylight.restconf.common.context.NormalizedNodeContext;
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.ContainerSchemaNode;
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.test.util.YangParserTestUtils;
51 import org.slf4j.Logger;
52 import org.slf4j.LoggerFactory;
53 import org.w3c.dom.Document;
54 import org.xml.sax.SAXException;
55
56 public final class TestRestconfUtils {
57
58     private static final Logger LOG = LoggerFactory.getLogger(TestRestconfUtils.class);
59
60     private TestRestconfUtils() {
61         throw new UnsupportedOperationException("Test utility class");
62     }
63
64     public static ControllerContext newControllerContext(final EffectiveModelContext schemaContext) {
65         return newControllerContext(schemaContext, null);
66     }
67
68     public static ControllerContext newControllerContext(final EffectiveModelContext schemaContext,
69             final DOMMountPoint mountInstance) {
70         final DOMMountPointService mockMountService = mock(DOMMountPointService.class);
71
72         if (mountInstance != null) {
73             doReturn(schemaContext).when(mountInstance).getEffectiveModelContext();
74             doCallRealMethod().when(mountInstance).getSchemaContext();
75             doReturn(Optional.ofNullable(mountInstance)).when(mockMountService).getMountPoint(
76                 any(YangInstanceIdentifier.class));
77         }
78
79         DOMSchemaService mockSchemaService = mock(DOMSchemaService.class);
80         doReturn(schemaContext).when(mockSchemaService).getGlobalContext();
81
82         DOMSchemaService mockDomSchemaService = mock(DOMSchemaService.class);
83         doReturn(ImmutableClassToInstanceMap.of()).when(mockDomSchemaService).getExtensions();
84
85         return ControllerContext.newInstance(mockSchemaService, mockMountService, mockDomSchemaService);
86     }
87
88     @SuppressWarnings("checkstyle:IllegalCatch")
89     public static EffectiveModelContext loadSchemaContext(final String yangPath,
90             final EffectiveModelContext schemaContext) {
91         try {
92             Preconditions.checkArgument(yangPath != null, "Path can not be null.");
93             Preconditions.checkArgument(!yangPath.isEmpty(), "Path can not be empty.");
94             if (schemaContext == null) {
95                 return YangParserTestUtils.parseYangFiles(TestRestconfUtils.loadFiles(yangPath));
96             } else {
97                 throw new UnsupportedOperationException("Unable to add new yang sources to existing schema context.");
98             }
99         } catch (final Exception e) {
100             LOG.error("Yang files at path: " + yangPath + " weren't loaded.", e);
101         }
102         return schemaContext;
103     }
104
105     public static NormalizedNodeContext loadNormalizedContextFromJsonFile() {
106         throw new AbstractMethodError("Not implemented yet");
107     }
108
109     @SuppressWarnings("checkstyle:IllegalCatch")
110     public static NormalizedNodeContext loadNormalizedContextFromXmlFile(final String pathToInputFile,
111             final String uri, final ControllerContext controllerContext) {
112         final InstanceIdentifierContext<?> iiContext = controllerContext.toInstanceIdentifier(uri);
113         final InputStream inputStream = TestJsonBodyWriter.class.getResourceAsStream(pathToInputFile);
114         try {
115             final Document doc = UntrustedXML.newDocumentBuilder().parse(inputStream);
116             final NormalizedNode<?, ?> nn = parse(iiContext, doc);
117             return new NormalizedNodeContext(iiContext, nn);
118         } catch (final Exception e) {
119             LOG.error("Load xml file " + pathToInputFile + " fail.", e);
120         }
121         return null;
122     }
123
124     private static NormalizedNode<?, ?> parse(final InstanceIdentifierContext<?> iiContext, final Document doc)
125             throws XMLStreamException, IOException, ParserConfigurationException, SAXException, URISyntaxException {
126         final SchemaNode schemaNodeContext = iiContext.getSchemaNode();
127         DataSchemaNode schemaNode = null;
128         if (schemaNodeContext instanceof RpcDefinition) {
129             if ("input".equalsIgnoreCase(doc.getDocumentElement().getLocalName())) {
130                 schemaNode = ((RpcDefinition) schemaNodeContext).getInput();
131             } else if ("output".equalsIgnoreCase(doc.getDocumentElement().getLocalName())) {
132                 schemaNode = ((RpcDefinition) schemaNodeContext).getOutput();
133             } else {
134                 throw new IllegalStateException("Unknown Rpc input node");
135             }
136
137         } else if (schemaNodeContext instanceof DataSchemaNode) {
138             schemaNode = (DataSchemaNode) schemaNodeContext;
139         } else {
140             throw new IllegalStateException("Unknow SchemaNode");
141         }
142
143         final String docRootElm = doc.getDocumentElement().getLocalName();
144         final String schemaNodeName = iiContext.getSchemaNode().getQName().getLocalName();
145
146         if (!schemaNodeName.equalsIgnoreCase(docRootElm)) {
147             for (final DataSchemaNode child : ((DataNodeContainer) schemaNode).getChildNodes()) {
148                 if (child.getQName().getLocalName().equalsIgnoreCase(docRootElm)) {
149                     schemaNode = child;
150                     break;
151                 }
152             }
153         }
154
155         final NormalizedNodeResult resultHolder = new NormalizedNodeResult();
156         final NormalizedNodeStreamWriter writer = ImmutableNormalizedNodeStreamWriter.from(resultHolder);
157         final XmlParserStream xmlParser = XmlParserStream.create(writer, iiContext.getSchemaContext(), schemaNode);
158
159         if (schemaNode instanceof ContainerSchemaNode || schemaNode instanceof ListSchemaNode) {
160             xmlParser.traverse(new DOMSource(doc.getDocumentElement()));
161             return resultHolder.getResult();
162         }
163         // FIXME : add another DataSchemaNode extensions e.g. LeafSchemaNode
164         return null;
165     }
166
167     public static Collection<File> loadFiles(final String resourceDirectory) throws FileNotFoundException {
168         final String path = TestRestconfUtils.class.getResource(resourceDirectory).getPath();
169         final File testDir = new File(path);
170         final String[] fileList = testDir.list();
171         final List<File> testFiles = new ArrayList<>();
172         if (fileList == null) {
173             throw new FileNotFoundException(resourceDirectory);
174         }
175         for (final String fileName : fileList) {
176             if (new File(testDir, fileName).isDirectory() == false) {
177                 testFiles.add(new File(testDir, fileName));
178             }
179         }
180         return testFiles;
181     }
182 }