c3bc2765c9c3900b30ac82dc3d53d83226c892cb
[netconf.git] / netconf / mdsal-netconf-connector / src / main / java / org / opendaylight / netconf / mdsal / connector / ops / get / AbstractGet.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.netconf.mdsal.connector.ops.get;
9
10 import static com.google.common.base.Preconditions.checkArgument;
11
12 import com.google.common.annotations.VisibleForTesting;
13 import java.io.IOException;
14 import java.util.Optional;
15 import javax.xml.stream.XMLOutputFactory;
16 import javax.xml.stream.XMLStreamException;
17 import javax.xml.stream.XMLStreamWriter;
18 import javax.xml.transform.dom.DOMResult;
19 import org.opendaylight.netconf.api.DocumentedException;
20 import org.opendaylight.netconf.api.xml.XmlElement;
21 import org.opendaylight.netconf.api.xml.XmlNetconfConstants;
22 import org.opendaylight.netconf.mdsal.connector.CurrentSchemaContext;
23 import org.opendaylight.netconf.mdsal.connector.ops.Datastore;
24 import org.opendaylight.netconf.util.mapping.AbstractSingletonNetconfOperation;
25 import org.opendaylight.yangtools.yang.common.ErrorSeverity;
26 import org.opendaylight.yangtools.yang.common.ErrorTag;
27 import org.opendaylight.yangtools.yang.common.ErrorType;
28 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
29 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
30 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
31 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
32 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeWriter;
33 import org.opendaylight.yangtools.yang.data.api.schema.stream.YangInstanceIdentifierWriter;
34 import org.opendaylight.yangtools.yang.data.codec.xml.XMLStreamNormalizedNodeStreamWriter;
35 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
36 import org.w3c.dom.Document;
37 import org.w3c.dom.Element;
38 import org.w3c.dom.Node;
39
40 // FIXME: seal when we have JDK17+
41 abstract class AbstractGet extends AbstractSingletonNetconfOperation {
42     private static final XMLOutputFactory XML_OUTPUT_FACTORY;
43     private static final String FILTER = "filter";
44
45     static {
46         XML_OUTPUT_FACTORY = XMLOutputFactory.newFactory();
47         XML_OUTPUT_FACTORY.setProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES, true);
48     }
49
50     private final CurrentSchemaContext schemaContext;
51     private final FilterContentValidator validator;
52
53     AbstractGet(final String netconfSessionIdForReporting, final CurrentSchemaContext schemaContext) {
54         super(netconfSessionIdForReporting);
55         this.schemaContext = schemaContext;
56         validator = new FilterContentValidator(schemaContext);
57     }
58
59     // FIXME: throw a DocumentedException
60     private Node transformNormalizedNode(final Document document, final NormalizedNode data,
61                                          final YangInstanceIdentifier dataRoot) {
62         final DOMResult result = new DOMResult(document.createElement(XmlNetconfConstants.DATA_KEY));
63         final XMLStreamWriter xmlWriter = getXmlStreamWriter(result);
64         final EffectiveModelContext currentContext = schemaContext.getCurrentContext();
65
66         final NormalizedNodeStreamWriter nnStreamWriter = XMLStreamNormalizedNodeStreamWriter.create(xmlWriter,
67             currentContext);
68
69         try {
70             if (dataRoot.isEmpty()) {
71                 writeRoot(nnStreamWriter, data);
72             } else {
73                 write(nnStreamWriter, currentContext, dataRoot.coerceParent(), data);
74             }
75         } catch (IOException e) {
76             throw new RuntimeException(e);
77         }
78
79         return result.getNode();
80     }
81
82     private static void write(final NormalizedNodeStreamWriter nnStreamWriter,
83             final EffectiveModelContext currentContext, final YangInstanceIdentifier parent, final NormalizedNode data)
84                 throws IOException {
85         try (var yiidWriter = YangInstanceIdentifierWriter.open(nnStreamWriter, currentContext, parent)) {
86             try (var nnWriter = NormalizedNodeWriter.forStreamWriter(nnStreamWriter, true)) {
87                 nnWriter.write(data);
88             }
89         }
90     }
91
92     private static void writeRoot(final NormalizedNodeStreamWriter nnStreamWriter, final NormalizedNode data)
93             throws IOException {
94         checkArgument(data instanceof ContainerNode, "Unexpected root data %s", data);
95
96         try (var nnWriter = NormalizedNodeWriter.forStreamWriter(nnStreamWriter, true)) {
97             for (var child : ((ContainerNode) data).body()) {
98                 nnWriter.write(child);
99             }
100         }
101     }
102
103     private static XMLStreamWriter getXmlStreamWriter(final DOMResult result) {
104         try {
105             return XML_OUTPUT_FACTORY.createXMLStreamWriter(result);
106         } catch (final XMLStreamException e) {
107             throw new RuntimeException(e);
108         }
109     }
110
111     final Element serializeNodeWithParentStructure(final Document document, final YangInstanceIdentifier dataRoot,
112                                                    final NormalizedNode node) {
113         return (Element) transformNormalizedNode(document, node, dataRoot);
114     }
115
116     /**
117      * Obtain data root according to filter from operation element.
118      *
119      * @param operationElement operation element
120      * @return if filter is present and not empty returns Optional of the InstanceIdentifier to the read location
121      *      in datastore. Empty filter returns Optional.absent() which should equal an empty <data/>
122      *      container in the response. If filter is not present we want to read the entire datastore - return ROOT.
123      * @throws DocumentedException if not possible to get identifier from filter
124      */
125     final Optional<YangInstanceIdentifier> getDataRootFromFilter(final XmlElement operationElement)
126             throws DocumentedException {
127         final Optional<XmlElement> filterElement = operationElement.getOnlyChildElementOptionally(FILTER);
128         if (filterElement.isPresent()) {
129             if (filterElement.get().getChildElements().size() == 0) {
130                 return Optional.empty();
131             }
132             return Optional.of(getInstanceIdentifierFromFilter(filterElement.get()));
133         }
134
135         return Optional.of(YangInstanceIdentifier.empty());
136     }
137
138     @VisibleForTesting
139     protected final YangInstanceIdentifier getInstanceIdentifierFromFilter(final XmlElement filterElement)
140             throws DocumentedException {
141
142         if (filterElement.getChildElements().size() != 1) {
143             throw new DocumentedException("Multiple filter roots not supported yet",
144                     ErrorType.APPLICATION, ErrorTag.OPERATION_NOT_SUPPORTED, ErrorSeverity.ERROR);
145         }
146
147         final XmlElement element = filterElement.getOnlyChildElement();
148         return validator.validate(element);
149     }
150
151     protected static final class GetConfigExecution {
152         private final Optional<Datastore> datastore;
153
154         GetConfigExecution(final Optional<Datastore> datastore) {
155             this.datastore = datastore;
156         }
157
158         static GetConfigExecution fromXml(final XmlElement xml, final String operationName) throws DocumentedException {
159             try {
160                 validateInputRpc(xml, operationName);
161             } catch (final DocumentedException e) {
162                 throw new DocumentedException("Incorrect RPC: " + e.getMessage(), e, e.getErrorType(), e.getErrorTag(),
163                         e.getErrorSeverity(), e.getErrorInfo());
164             }
165
166             final Optional<Datastore> sourceDatastore;
167             try {
168                 sourceDatastore = parseSource(xml);
169             } catch (final DocumentedException e) {
170                 throw new DocumentedException("Get-config source attribute error: " + e.getMessage(), e,
171                         e.getErrorType(), e.getErrorTag(), e.getErrorSeverity(), e.getErrorInfo());
172             }
173
174             return new GetConfigExecution(sourceDatastore);
175         }
176
177         private static Optional<Datastore> parseSource(final XmlElement xml) throws DocumentedException {
178             final Optional<XmlElement> sourceElement = xml.getOnlyChildElementOptionally(XmlNetconfConstants.SOURCE_KEY,
179                     XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0);
180             return sourceElement.isPresent()
181                     ? Optional.of(Datastore.valueOf(sourceElement.get().getOnlyChildElement().getName()))
182                     : Optional.empty();
183         }
184
185         private static void validateInputRpc(final XmlElement xml, final String operationName) throws
186                 DocumentedException {
187             xml.checkName(operationName);
188             xml.checkNamespace(XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0);
189         }
190
191         public Optional<Datastore> getDatastore() {
192             return datastore;
193         }
194     }
195 }