Correct root vs. nested writeout
[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 public 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     // FIXME: hide this field
51     protected final CurrentSchemaContext schemaContext;
52     private final FilterContentValidator validator;
53
54     // FIXME: package-private
55     protected AbstractGet(final String netconfSessionIdForReporting, final CurrentSchemaContext schemaContext) {
56         super(netconfSessionIdForReporting);
57         this.schemaContext = schemaContext;
58         validator = new FilterContentValidator(schemaContext);
59     }
60
61     // FIXME: hide this method
62     // FIXME: throw a DocumentedException
63     protected Node transformNormalizedNode(final Document document, final NormalizedNode data,
64                                            final YangInstanceIdentifier dataRoot) {
65         final DOMResult result = new DOMResult(document.createElement(XmlNetconfConstants.DATA_KEY));
66         final XMLStreamWriter xmlWriter = getXmlStreamWriter(result);
67         final EffectiveModelContext currentContext = schemaContext.getCurrentContext();
68
69         final NormalizedNodeStreamWriter nnStreamWriter = XMLStreamNormalizedNodeStreamWriter.create(xmlWriter,
70             currentContext);
71
72         try {
73             if (dataRoot.isEmpty()) {
74                 writeRoot(nnStreamWriter, data);
75             } else {
76                 write(nnStreamWriter, currentContext, dataRoot.coerceParent(), data);
77             }
78         } catch (IOException e) {
79             throw new RuntimeException(e);
80         }
81
82         return result.getNode();
83     }
84
85     private static void write(final NormalizedNodeStreamWriter nnStreamWriter,
86             final EffectiveModelContext currentContext, final YangInstanceIdentifier parent, final NormalizedNode data)
87                 throws IOException {
88         try (var yiidWriter = YangInstanceIdentifierWriter.open(nnStreamWriter, currentContext, parent)) {
89             try (var nnWriter = NormalizedNodeWriter.forStreamWriter(nnStreamWriter, true)) {
90                 nnWriter.write(data);
91             }
92         }
93     }
94
95     private static void writeRoot(final NormalizedNodeStreamWriter nnStreamWriter, final NormalizedNode data)
96             throws IOException {
97         checkArgument(data instanceof ContainerNode, "Unexpected root data %s", data);
98
99         try (var nnWriter = NormalizedNodeWriter.forStreamWriter(nnStreamWriter, true)) {
100             for (var child : ((ContainerNode) data).body()) {
101                 nnWriter.write(child);
102             }
103         }
104     }
105
106     private static XMLStreamWriter getXmlStreamWriter(final DOMResult result) {
107         try {
108             return XML_OUTPUT_FACTORY.createXMLStreamWriter(result);
109         } catch (final XMLStreamException e) {
110             throw new RuntimeException(e);
111         }
112     }
113
114     protected Element serializeNodeWithParentStructure(final Document document, final YangInstanceIdentifier dataRoot,
115                                                        final NormalizedNode node) {
116         return (Element) transformNormalizedNode(document, node, dataRoot);
117     }
118
119     /**
120      * Obtain data root according to filter from operation element.
121      *
122      * @param operationElement operation element
123      * @return if filter is present and not empty returns Optional of the InstanceIdentifier to the read location
124      *      in datastore. Empty filter returns Optional.absent() which should equal an empty <data/>
125      *      container in the response. If filter is not present we want to read the entire datastore - return ROOT.
126      * @throws DocumentedException if not possible to get identifier from filter
127      */
128     protected Optional<YangInstanceIdentifier> getDataRootFromFilter(final XmlElement operationElement)
129             throws DocumentedException {
130         final Optional<XmlElement> filterElement = operationElement.getOnlyChildElementOptionally(FILTER);
131         if (filterElement.isPresent()) {
132             if (filterElement.get().getChildElements().size() == 0) {
133                 return Optional.empty();
134             }
135             return Optional.of(getInstanceIdentifierFromFilter(filterElement.get()));
136         }
137
138         return Optional.of(YangInstanceIdentifier.empty());
139     }
140
141     @VisibleForTesting
142     protected YangInstanceIdentifier getInstanceIdentifierFromFilter(final XmlElement filterElement)
143             throws DocumentedException {
144
145         if (filterElement.getChildElements().size() != 1) {
146             throw new DocumentedException("Multiple filter roots not supported yet",
147                     ErrorType.APPLICATION, ErrorTag.OPERATION_NOT_SUPPORTED, ErrorSeverity.ERROR);
148         }
149
150         final XmlElement element = filterElement.getOnlyChildElement();
151         return validator.validate(element);
152     }
153
154     protected static final class GetConfigExecution {
155         private final Optional<Datastore> datastore;
156
157         GetConfigExecution(final Optional<Datastore> datastore) {
158             this.datastore = datastore;
159         }
160
161         static GetConfigExecution fromXml(final XmlElement xml, final String operationName) throws DocumentedException {
162             try {
163                 validateInputRpc(xml, operationName);
164             } catch (final DocumentedException e) {
165                 throw new DocumentedException("Incorrect RPC: " + e.getMessage(), e, e.getErrorType(), e.getErrorTag(),
166                         e.getErrorSeverity(), e.getErrorInfo());
167             }
168
169             final Optional<Datastore> sourceDatastore;
170             try {
171                 sourceDatastore = parseSource(xml);
172             } catch (final DocumentedException e) {
173                 throw new DocumentedException("Get-config source attribute error: " + e.getMessage(), e,
174                         e.getErrorType(), e.getErrorTag(), e.getErrorSeverity(), e.getErrorInfo());
175             }
176
177             return new GetConfigExecution(sourceDatastore);
178         }
179
180         private static Optional<Datastore> parseSource(final XmlElement xml) throws DocumentedException {
181             final Optional<XmlElement> sourceElement = xml.getOnlyChildElementOptionally(XmlNetconfConstants.SOURCE_KEY,
182                     XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0);
183             return sourceElement.isPresent()
184                     ? Optional.of(Datastore.valueOf(sourceElement.get().getOnlyChildElement().getName()))
185                     : Optional.empty();
186         }
187
188         private static void validateInputRpc(final XmlElement xml, final String operationName) throws
189                 DocumentedException {
190             xml.checkName(operationName);
191             xml.checkNamespace(XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0);
192         }
193
194         public Optional<Datastore> getDatastore() {
195             return datastore;
196         }
197     }
198 }