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
9 package org.opendaylight.controller.md.sal.rest.common;
12 import java.io.FileNotFoundException;
13 import java.io.InputStream;
14 import java.net.URISyntaxException;
15 import java.util.ArrayList;
16 import java.util.Collection;
17 import java.util.Collections;
18 import java.util.List;
20 import javax.xml.parsers.DocumentBuilder;
21 import javax.xml.parsers.DocumentBuilderFactory;
22 import javax.xml.parsers.ParserConfigurationException;
24 import org.opendaylight.controller.sal.rest.impl.test.providers.TestJsonBodyWriter;
25 import org.opendaylight.netconf.sal.restconf.impl.ControllerContext;
26 import org.opendaylight.netconf.sal.restconf.impl.InstanceIdentifierContext;
27 import org.opendaylight.netconf.sal.restconf.impl.NormalizedNodeContext;
28 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
29 import org.opendaylight.yangtools.yang.data.impl.codec.xml.XmlUtils;
30 import org.opendaylight.yangtools.yang.data.impl.schema.transform.dom.parser.DomToNormalizedNodeParserFactory;
31 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
32 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
33 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
34 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
35 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
36 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
37 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
38 import org.opendaylight.yangtools.yang.parser.spi.meta.ReactorException;
39 import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
40 import org.opendaylight.yangtools.yang.parser.stmt.reactor.CrossSourceStatementReactor;
41 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.YangInferencePipeline;
42 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.YangStatementSourceImpl;
43 import org.opendaylight.yangtools.yang.parser.util.NamedFileInputStream;
44 import org.slf4j.Logger;
45 import org.slf4j.LoggerFactory;
46 import org.w3c.dom.Document;
47 import org.w3c.dom.Element;
49 import com.google.common.base.Preconditions;
53 * org.opendaylight.controller.md.sal.rest.common
57 * @author <a href="mailto:vdemcak@cisco.com">Vaclav Demcak</a>
59 * Created: Mar 7, 2015
61 public class TestRestconfUtils {
63 private static final Logger LOG = LoggerFactory.getLogger(TestRestconfUtils.class);
65 private static final DocumentBuilderFactory BUILDERFACTORY;
68 final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
70 factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
71 factory.setFeature("http://xml.org/sax/features/external-general-entities", false);
72 factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
73 factory.setXIncludeAware(false);
74 factory.setExpandEntityReferences(false);
75 } catch (final ParserConfigurationException e) {
76 throw new ExceptionInInitializerError(e);
78 factory.setNamespaceAware(true);
79 factory.setCoalescing(true);
80 factory.setIgnoringElementContentWhitespace(true);
81 factory.setIgnoringComments(true);
82 BUILDERFACTORY = factory;
85 private TestRestconfUtils () {
86 throw new UnsupportedOperationException("Test utility class");
89 public static SchemaContext loadSchemaContext(final String yangPath, final SchemaContext schemaContext) {
91 Preconditions.checkArgument(yangPath != null, "Path can not be null.");
92 Preconditions.checkArgument(( ! yangPath.isEmpty()), "Path can not be empty.");
93 if (schemaContext == null) {
94 return loadSchemaContext(yangPath);
96 throw new UnsupportedOperationException("Unable to add new yang sources to existing schema context.");
99 catch (final Exception e) {
100 LOG.error("Yang files at path: " + yangPath + " weren't loaded.");
102 return schemaContext;
105 public static NormalizedNodeContext loadNormalizedContextFromJsonFile() {
106 throw new AbstractMethodError("Not implemented yet");
109 public static NormalizedNodeContext loadNormalizedContextFromXmlFile(final String pathToInputFile, final String uri) {
110 final InstanceIdentifierContext<?> iiContext = ControllerContext.getInstance().toInstanceIdentifier(uri);
111 final InputStream inputStream = TestJsonBodyWriter.class.getResourceAsStream(pathToInputFile);
113 final DocumentBuilder dBuilder = BUILDERFACTORY.newDocumentBuilder();
114 final Document doc = dBuilder.parse(inputStream);
115 final NormalizedNode<?, ?> nn = parse(iiContext, doc);
116 return new NormalizedNodeContext(iiContext, nn);
118 catch (final Exception e) {
119 LOG.error("Load xml file " + pathToInputFile + " fail.", e);
124 private static NormalizedNode<?, ?> parse(final InstanceIdentifierContext<?> iiContext, final Document doc) {
125 final List<Element> elements = Collections.singletonList(doc.getDocumentElement());
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();
134 throw new IllegalStateException("Unknown Rpc input node");
137 } else if (schemaNodeContext instanceof DataSchemaNode) {
138 schemaNode = (DataSchemaNode) schemaNodeContext;
140 throw new IllegalStateException("Unknow SchemaNode");
143 final String docRootElm = doc.getDocumentElement().getLocalName();
144 final String schemaNodeName = iiContext.getSchemaNode().getQName().getLocalName();
146 if (!schemaNodeName.equalsIgnoreCase(docRootElm)) {
147 final Collection<DataSchemaNode> children = ((DataNodeContainer) schemaNode).getChildNodes();
148 for (final DataSchemaNode child : children) {
149 if (child.getQName().getLocalName().equalsIgnoreCase(docRootElm)) {
155 final DomToNormalizedNodeParserFactory parserFactory =
156 DomToNormalizedNodeParserFactory.getInstance(XmlUtils.DEFAULT_XML_CODEC_PROVIDER, iiContext.getSchemaContext());
158 if(schemaNode instanceof ContainerSchemaNode) {
159 return parserFactory.getContainerNodeParser().parse(Collections.singletonList(doc.getDocumentElement()), (ContainerSchemaNode) schemaNode);
160 } else if(schemaNode instanceof ListSchemaNode) {
161 final ListSchemaNode casted = (ListSchemaNode) schemaNode;
162 return parserFactory.getMapEntryNodeParser().parse(elements, casted);
163 } // FIXME : add another DataSchemaNode extensions e.g. LeafSchemaNode
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<File>();
172 if (fileList == null) {
173 throw new FileNotFoundException(resourceDirectory);
175 for (int i = 0; i < fileList.length; i++) {
176 final String fileName = fileList[i];
177 if (new File(testDir, fileName).isDirectory() == false) {
178 testFiles.add(new File(testDir, fileName));
184 public static SchemaContext loadSchemaContext(String resourceDirectory)
185 throws SourceException, ReactorException, FileNotFoundException,
187 return parseYangSources(loadFiles(resourceDirectory));
190 public static SchemaContext parseYangSources(Collection<File> testFiles)
191 throws SourceException, ReactorException, FileNotFoundException {
192 CrossSourceStatementReactor.BuildAction reactor = YangInferencePipeline.RFC6020_REACTOR
194 for (File testFile : testFiles) {
195 reactor.addSource(new YangStatementSourceImpl(
196 new NamedFileInputStream(testFile, testFile.getPath())));
199 return reactor.buildEffective();