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