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