2 * Copyright (c) 2014 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
8 package org.opendaylight.netconf.sal.connect.netconf.util;
10 import static org.opendaylight.netconf.util.NetconfUtil.NETCONF_DATA_QNAME;
11 import static org.opendaylight.netconf.util.NetconfUtil.NETCONF_QNAME;
13 import com.google.common.base.Preconditions;
14 import com.google.common.collect.ImmutableList;
15 import com.google.common.collect.ImmutableMap;
16 import java.io.IOException;
18 import java.time.Instant;
19 import java.time.format.DateTimeParseException;
20 import java.util.AbstractMap.SimpleEntry;
21 import java.util.ArrayDeque;
22 import java.util.Collection;
23 import java.util.Deque;
24 import java.util.Iterator;
25 import java.util.List;
26 import java.util.Locale;
28 import java.util.Map.Entry;
29 import java.util.Optional;
30 import javax.xml.stream.XMLStreamException;
31 import javax.xml.stream.XMLStreamWriter;
32 import javax.xml.transform.dom.DOMResult;
33 import javax.xml.transform.dom.DOMSource;
34 import org.eclipse.jdt.annotation.NonNull;
35 import org.opendaylight.mdsal.dom.api.DOMDataTreeIdentifier;
36 import org.opendaylight.netconf.api.DocumentedException;
37 import org.opendaylight.netconf.api.FailedNetconfMessage;
38 import org.opendaylight.netconf.api.ModifyAction;
39 import org.opendaylight.netconf.api.NetconfDocumentedException;
40 import org.opendaylight.netconf.api.NetconfMessage;
41 import org.opendaylight.netconf.api.xml.XmlElement;
42 import org.opendaylight.netconf.api.xml.XmlUtil;
43 import org.opendaylight.netconf.notifications.NetconfNotification;
44 import org.opendaylight.netconf.sal.connect.util.MessageCounter;
45 import org.opendaylight.netconf.util.NetconfUtil;
46 import org.opendaylight.netconf.util.messages.NetconfMessageUtil;
47 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netconf.base._1._0.rev110601.edit.config.input.EditContent;
48 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netconf.notification._1._0.rev080714.CreateSubscriptionInput;
49 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.monitoring.rev101004.NetconfState;
50 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.notifications.rev120206.NetconfCapabilityChange;
51 import org.opendaylight.yangtools.rfc7952.data.api.NormalizedMetadata;
52 import org.opendaylight.yangtools.rfc7952.data.util.ImmutableNormalizedMetadata;
53 import org.opendaylight.yangtools.rfc7952.data.util.ImmutableNormalizedMetadata.Builder;
54 import org.opendaylight.yangtools.yang.common.ErrorSeverity;
55 import org.opendaylight.yangtools.yang.common.ErrorTag;
56 import org.opendaylight.yangtools.yang.common.ErrorType;
57 import org.opendaylight.yangtools.yang.common.QName;
58 import org.opendaylight.yangtools.yang.common.RpcError;
59 import org.opendaylight.yangtools.yang.common.RpcResult;
60 import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
61 import org.opendaylight.yangtools.yang.common.XMLNamespace;
62 import org.opendaylight.yangtools.yang.common.YangConstants;
63 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
64 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
65 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
66 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeWithValue;
67 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
68 import org.opendaylight.yangtools.yang.data.api.schema.AnyxmlNode;
69 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
70 import org.opendaylight.yangtools.yang.data.api.schema.DOMSourceAnyxmlNode;
71 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
72 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
73 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
74 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeWriter;
75 import org.opendaylight.yangtools.yang.data.api.schema.stream.YangInstanceIdentifierWriter;
76 import org.opendaylight.yangtools.yang.data.codec.xml.XMLStreamNormalizedNodeStreamWriter;
77 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
78 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNormalizedNodeStreamWriter;
79 import org.opendaylight.yangtools.yang.data.impl.schema.NormalizedNodeResult;
80 import org.opendaylight.yangtools.yang.data.impl.schema.SchemaOrderedNormalizedNodeWriter;
81 import org.opendaylight.yangtools.yang.data.util.DataSchemaContextNode;
82 import org.opendaylight.yangtools.yang.data.util.DataSchemaContextTree;
83 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
84 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier.Absolute;
85 import org.opendaylight.yangtools.yang.model.util.SchemaInferenceStack;
86 import org.slf4j.Logger;
87 import org.slf4j.LoggerFactory;
88 import org.w3c.dom.Document;
89 import org.w3c.dom.Element;
91 public final class NetconfMessageTransformUtil {
93 private static final Logger LOG = LoggerFactory.getLogger(NetconfMessageTransformUtil.class);
95 public static final String MESSAGE_ID_PREFIX = "m";
96 public static final String MESSAGE_ID_ATTR = "message-id";
98 public static final @NonNull QName CREATE_SUBSCRIPTION_RPC_QNAME =
99 QName.create(CreateSubscriptionInput.QNAME, "create-subscription").intern();
100 private static final String SUBTREE = "subtree";
102 // Blank document used for creation of new DOM nodes
103 private static final Document BLANK_DOCUMENT = XmlUtil.newDocument();
104 public static final String EVENT_TIME = "eventTime";
106 private NetconfMessageTransformUtil() {
110 public static final @NonNull QName IETF_NETCONF_MONITORING =
111 QName.create(NetconfState.QNAME, "ietf-netconf-monitoring").intern();
112 public static final @NonNull QName GET_DATA_QNAME = QName.create(IETF_NETCONF_MONITORING, "data").intern();
113 public static final @NonNull QName GET_SCHEMA_QNAME = QName.create(IETF_NETCONF_MONITORING, "get-schema").intern();
114 public static final @NonNull QName IETF_NETCONF_MONITORING_SCHEMA_FORMAT =
115 QName.create(IETF_NETCONF_MONITORING, "format").intern();
116 public static final @NonNull QName IETF_NETCONF_MONITORING_SCHEMA_LOCATION =
117 QName.create(IETF_NETCONF_MONITORING, "location").intern();
118 public static final @NonNull QName IETF_NETCONF_MONITORING_SCHEMA_IDENTIFIER =
119 QName.create(IETF_NETCONF_MONITORING, "identifier").intern();
120 public static final @NonNull QName IETF_NETCONF_MONITORING_SCHEMA_VERSION =
121 QName.create(IETF_NETCONF_MONITORING, "version").intern();
122 public static final @NonNull QName IETF_NETCONF_MONITORING_SCHEMA_NAMESPACE =
123 QName.create(IETF_NETCONF_MONITORING, "namespace").intern();
125 public static final @NonNull QName IETF_NETCONF_NOTIFICATIONS =
126 QName.create(NetconfCapabilityChange.QNAME, "ietf-netconf-notifications").intern();
128 public static final XMLNamespace NETCONF_URI = NETCONF_QNAME.getNamespace();
130 public static final @NonNull NodeIdentifier NETCONF_DATA_NODEID = NodeIdentifier.create(NETCONF_DATA_QNAME);
132 public static final @NonNull QName NETCONF_RPC_REPLY_QNAME = QName.create(NETCONF_QNAME, "rpc-reply").intern();
133 public static final @NonNull NodeIdentifier NETCONF_RPC_REPLY_NODEID =
134 NodeIdentifier.create(NETCONF_RPC_REPLY_QNAME);
136 public static final @NonNull QName NETCONF_OK_QNAME = QName.create(NETCONF_QNAME, "ok").intern();
137 public static final @NonNull QName NETCONF_ERROR_OPTION_QNAME =
138 QName.create(NETCONF_QNAME, "error-option").intern();
139 public static final @NonNull NodeIdentifier NETCONF_ERROR_OPTION_NODEID =
140 NodeIdentifier.create(NETCONF_ERROR_OPTION_QNAME);
141 public static final @NonNull QName NETCONF_RUNNING_QNAME = QName.create(NETCONF_QNAME, "running").intern();
142 public static final @NonNull QName NETCONF_SOURCE_QNAME = QName.create(NETCONF_QNAME, "source").intern();
143 public static final @NonNull NodeIdentifier NETCONF_SOURCE_NODEID = NodeIdentifier.create(NETCONF_SOURCE_QNAME);
144 public static final @NonNull QName NETCONF_CANDIDATE_QNAME = QName.create(NETCONF_QNAME, "candidate").intern();
145 public static final @NonNull QName NETCONF_TARGET_QNAME = QName.create(NETCONF_QNAME, "target").intern();
146 public static final @NonNull NodeIdentifier NETCONF_TARGET_NODEID = NodeIdentifier.create(NETCONF_TARGET_QNAME);
147 public static final @NonNull QName NETCONF_CONFIG_QNAME = QName.create(NETCONF_QNAME, "config").intern();
148 public static final @NonNull NodeIdentifier NETCONF_CONFIG_NODEID = NodeIdentifier.create(NETCONF_CONFIG_QNAME);
150 public static final @NonNull QName NETCONF_COMMIT_QNAME = QName.create(NETCONF_QNAME, "commit").intern();
151 public static final @NonNull Absolute NETCONF_COMMIT_PATH = toPath(NETCONF_COMMIT_QNAME);
152 public static final @NonNull QName NETCONF_VALIDATE_QNAME = QName.create(NETCONF_QNAME, "validate").intern();
153 public static final @NonNull NodeIdentifier NETCONF_VALIDATE_NODEID = NodeIdentifier.create(NETCONF_VALIDATE_QNAME);
154 public static final @NonNull Absolute NETCONF_VALIDATE_PATH = toPath(NETCONF_VALIDATE_QNAME);
155 public static final @NonNull QName NETCONF_COPY_CONFIG_QNAME = QName.create(NETCONF_QNAME, "copy-config").intern();
156 public static final @NonNull NodeIdentifier NETCONF_COPY_CONFIG_NODEID =
157 NodeIdentifier.create(NETCONF_COPY_CONFIG_QNAME);
158 public static final @NonNull Absolute NETCONF_COPY_CONFIG_PATH = toPath(NETCONF_COPY_CONFIG_QNAME);
160 public static final @NonNull QName NETCONF_OPERATION_QNAME = QName.create(NETCONF_QNAME, "operation").intern();
161 private static final @NonNull QName NETCONF_OPERATION_QNAME_LEGACY =
162 NETCONF_OPERATION_QNAME.withoutRevision().intern();
163 public static final @NonNull QName NETCONF_DEFAULT_OPERATION_QNAME =
164 QName.create(NETCONF_OPERATION_QNAME, "default-operation").intern();
165 public static final @NonNull NodeIdentifier NETCONF_DEFAULT_OPERATION_NODEID =
166 NodeIdentifier.create(NETCONF_DEFAULT_OPERATION_QNAME);
167 public static final @NonNull QName NETCONF_EDIT_CONFIG_QNAME = QName.create(NETCONF_QNAME, "edit-config").intern();
168 public static final @NonNull NodeIdentifier NETCONF_EDIT_CONFIG_NODEID =
169 NodeIdentifier.create(NETCONF_EDIT_CONFIG_QNAME);
170 public static final @NonNull Absolute NETCONF_EDIT_CONFIG_PATH = toPath(NETCONF_EDIT_CONFIG_QNAME);
171 public static final @NonNull QName NETCONF_GET_CONFIG_QNAME = QName.create(NETCONF_QNAME, "get-config");
172 public static final @NonNull NodeIdentifier NETCONF_GET_CONFIG_NODEID =
173 NodeIdentifier.create(NETCONF_GET_CONFIG_QNAME);
174 public static final @NonNull Absolute NETCONF_GET_CONFIG_PATH = toPath(NETCONF_GET_CONFIG_QNAME);
175 public static final @NonNull QName NETCONF_DISCARD_CHANGES_QNAME = QName.create(NETCONF_QNAME, "discard-changes");
176 public static final @NonNull Absolute NETCONF_DISCARD_CHANGES_PATH = toPath(NETCONF_DISCARD_CHANGES_QNAME);
177 public static final @NonNull QName NETCONF_TYPE_QNAME = QName.create(NETCONF_QNAME, "type").intern();
178 public static final @NonNull QName NETCONF_FILTER_QNAME = QName.create(NETCONF_QNAME, "filter").intern();
179 public static final @NonNull QName NETCONF_GET_QNAME = QName.create(NETCONF_QNAME, "get").intern();
180 public static final @NonNull NodeIdentifier NETCONF_GET_NODEID = NodeIdentifier.create(NETCONF_GET_QNAME);
181 public static final @NonNull Absolute NETCONF_GET_PATH = toPath(NETCONF_GET_QNAME);
182 public static final @NonNull QName NETCONF_RPC_QNAME = QName.create(NETCONF_QNAME, "rpc").intern();
183 public static final QName YANG_QNAME = null;
184 public static final URI NETCONF_ACTION_NAMESPACE = URI.create("urn:ietf:params:xml:ns:yang:1");
185 public static final String NETCONF_ACTION = "action";
187 public static final URI NETCONF_ROLLBACK_ON_ERROR_URI = URI
188 .create("urn:ietf:params:netconf:capability:rollback-on-error:1.0");
189 public static final String ROLLBACK_ON_ERROR_OPTION = "rollback-on-error";
191 public static final URI NETCONF_CANDIDATE_URI = URI
192 .create("urn:ietf:params:netconf:capability:candidate:1.0");
194 public static final URI NETCONF_NOTIFICATONS_URI = URI
195 .create("urn:ietf:params:netconf:capability:notification:1.0");
197 public static final URI NETCONF_RUNNING_WRITABLE_URI = URI
198 .create("urn:ietf:params:netconf:capability:writable-running:1.0");
200 public static final @NonNull QName NETCONF_LOCK_QNAME = QName.create(NETCONF_QNAME, "lock").intern();
201 public static final @NonNull NodeIdentifier NETCONF_LOCK_NODEID = NodeIdentifier.create(NETCONF_LOCK_QNAME);
202 public static final @NonNull Absolute NETCONF_LOCK_PATH = toPath(NETCONF_LOCK_QNAME);
203 public static final @NonNull QName NETCONF_UNLOCK_QNAME = QName.create(NETCONF_QNAME, "unlock").intern();
204 public static final @NonNull NodeIdentifier NETCONF_UNLOCK_NODEID = NodeIdentifier.create(NETCONF_UNLOCK_QNAME);
205 public static final @NonNull Absolute NETCONF_UNLOCK_PATH = toPath(NETCONF_UNLOCK_QNAME);
207 public static final @NonNull NodeIdentifier EDIT_CONTENT_NODEID = NodeIdentifier.create(EditContent.QNAME);
209 // Discard changes message
210 public static final @NonNull ContainerNode DISCARD_CHANGES_RPC_CONTENT = Builders.containerBuilder()
211 .withNodeIdentifier(NodeIdentifier.create(NETCONF_DISCARD_CHANGES_QNAME)).build();
213 // Commit changes message
214 public static final @NonNull ContainerNode COMMIT_RPC_CONTENT = Builders.containerBuilder()
215 .withNodeIdentifier(NodeIdentifier.create(NETCONF_COMMIT_QNAME)).build();
218 public static final @NonNull ContainerNode GET_RPC_CONTENT = Builders.containerBuilder()
219 .withNodeIdentifier(NETCONF_GET_NODEID).build();
221 // Create-subscription changes message
222 public static final @NonNull ContainerNode CREATE_SUBSCRIPTION_RPC_CONTENT = Builders.containerBuilder()
223 .withNodeIdentifier(NodeIdentifier.create(CREATE_SUBSCRIPTION_RPC_QNAME)).build();
225 public static final @NonNull Absolute CREATE_SUBSCRIPTION_RPC_PATH = toPath(CREATE_SUBSCRIPTION_RPC_QNAME);
227 public static final @NonNull NodeIdentifier NETCONF_FILTER_NODEID = NodeIdentifier.create(NETCONF_FILTER_QNAME);
229 public static final @NonNull AnyxmlNode<?> EMPTY_FILTER = buildFilterStructure(getNetconfFilterElement());
232 * Creation of the subtree filter structure using {@link YangInstanceIdentifier} path.
234 * @param identifier parent path / query
235 * @param ctx mountpoint schema context
236 * @return created DOM structure with subtree filter
238 public static AnyxmlNode<?> toFilterStructure(final YangInstanceIdentifier identifier,
239 final EffectiveModelContext ctx) {
240 final Element element = getNetconfFilterElement();
242 NetconfUtil.writeFilter(identifier, new DOMResult(element), ctx, null);
243 } catch (IOException | XMLStreamException e) {
244 throw new IllegalStateException("Unable to serialize filter element for path " + identifier, e);
246 return buildFilterStructure(element);
250 * Creation of the subtree filter structure using list of parent {@link YangInstanceIdentifier}
251 * and specific selection fields. Field paths are relative to parent query path.
253 * @param fieldsFilters list of: parent path and selection fields
254 * @param ctx mountpoint schema context
255 * @return created DOM structure with subtree filter
257 public static AnyxmlNode<?> toFilterStructure(final List<FieldsFilter> fieldsFilters,
258 final EffectiveModelContext ctx) {
259 Preconditions.checkState(!fieldsFilters.isEmpty(), "An empty list of subtree filters is not allowed");
260 final Element element = getNetconfFilterElement();
262 for (final FieldsFilter filter : fieldsFilters) {
264 NetconfUtil.writeFilter(filter.path(), new DOMResult(element), ctx, null, filter.fields());
265 } catch (IOException | XMLStreamException e) {
266 throw new IllegalStateException(String.format(
267 "Unable to serialize filter element for path %s with fields: %s",
268 filter.path(), filter.fields()), e);
271 return buildFilterStructure(element);
274 private static Element getNetconfFilterElement() {
275 final Element element = XmlUtil.createElement(BLANK_DOCUMENT, NETCONF_FILTER_QNAME.getLocalName(),
276 Optional.of(NETCONF_FILTER_QNAME.getNamespace().toString()));
277 element.setAttributeNS(NETCONF_FILTER_QNAME.getNamespace().toString(), NETCONF_TYPE_QNAME.getLocalName(),
282 private static AnyxmlNode<?> buildFilterStructure(final Element element) {
283 return Builders.anyXmlBuilder()
284 .withNodeIdentifier(NETCONF_FILTER_NODEID)
285 .withValue(new DOMSource(element))
289 public static void checkValidReply(final NetconfMessage input, final NetconfMessage output)
290 throws NetconfDocumentedException {
291 final String inputMsgId = input.getDocument().getDocumentElement().getAttribute(MESSAGE_ID_ATTR);
292 final String outputMsgId = output.getDocument().getDocumentElement().getAttribute(MESSAGE_ID_ATTR);
294 if (!inputMsgId.equals(outputMsgId)) {
295 throw new NetconfDocumentedException("Response message contained unknown \"message-id\"", null,
296 ErrorType.PROTOCOL, ErrorTag.BAD_ATTRIBUTE, ErrorSeverity.ERROR,
297 ImmutableMap.of("actual-message-id", outputMsgId, "expected-message-id", inputMsgId));
301 public static void checkSuccessReply(final NetconfMessage output) throws NetconfDocumentedException {
302 if (NetconfMessageUtil.isErrorMessage(output)) {
303 throw NetconfDocumentedException.fromXMLDocument(output.getDocument());
307 public static RpcError toRpcError(final NetconfDocumentedException ex) {
308 final StringBuilder infoBuilder = new StringBuilder();
309 final Map<String, String> errorInfo = ex.getErrorInfo();
310 if (errorInfo != null) {
311 for (final Entry<String, String> e : errorInfo.entrySet()) {
312 infoBuilder.append('<').append(e.getKey()).append('>').append(e.getValue())
313 .append("</").append(e.getKey()).append('>');
318 return ex.getErrorSeverity() == ErrorSeverity.ERROR
319 ? RpcResultBuilder.newError(ex.getErrorType(), ex.getErrorTag(),
320 ex.getLocalizedMessage(), null, infoBuilder.toString(), ex.getCause())
321 : RpcResultBuilder.newWarning(ex.getErrorType(), ex.getErrorTag(),
322 ex.getLocalizedMessage(), null, infoBuilder.toString(), ex.getCause());
325 public static NodeIdentifier toId(final PathArgument qname) {
326 return qname instanceof NodeIdentifier ? (NodeIdentifier) qname : toId(qname.getNodeType());
329 public static NodeIdentifier toId(final QName nodeType) {
330 return new NodeIdentifier(nodeType);
333 public static Element getDataSubtree(final Document doc) {
334 return (Element) doc.getElementsByTagNameNS(NETCONF_URI.toString(), "data").item(0);
337 public static boolean isDataRetrievalOperation(final QName rpc) {
338 return NETCONF_URI.equals(rpc.getNamespace())
339 && (NETCONF_GET_CONFIG_QNAME.getLocalName().equals(rpc.getLocalName())
340 || NETCONF_GET_QNAME.getLocalName().equals(rpc.getLocalName()));
344 public static @NonNull ContainerNode wrap(final QName name, final DataContainerChild... node) {
345 return wrap(toId(name), node);
348 public static @NonNull ContainerNode wrap(final NodeIdentifier name, final DataContainerChild... node) {
349 return Builders.containerBuilder().withNodeIdentifier(name).withValue(ImmutableList.copyOf(node)).build();
353 * Create edit-config structure to invoke {@code operation} with {@code lastChildOverride} data on {@code dataPath}.
355 * @param ctx {@link EffectiveModelContext} device's model context
356 * @param dataPath {@link YangInstanceIdentifier} path to data in device's data-store
357 * @param operation Optional of {@link ModifyAction} action to be invoked
358 * @param lastChildOverride Optional of {@code NormalizedNode} data on which action will be invoked
359 * @return {@link DOMSourceAnyxmlNode} containing edit-config structure
361 public static DOMSourceAnyxmlNode createEditConfigAnyxml(
362 final EffectiveModelContext ctx, final YangInstanceIdentifier dataPath,
363 final Optional<ModifyAction> operation, final Optional<NormalizedNode> lastChildOverride) {
364 if (dataPath.isEmpty()) {
365 Preconditions.checkArgument(lastChildOverride.isPresent(),
366 "Data has to be present when creating structure for top level element");
367 Preconditions.checkArgument(lastChildOverride.get() instanceof DataContainerChild,
368 "Data has to be either container or a list node when creating structure for top level element, "
369 + "but was: %s", lastChildOverride.get());
372 final var element = XmlUtil.createElement(BLANK_DOCUMENT, NETCONF_CONFIG_QNAME.getLocalName(),
373 Optional.of(NETCONF_CONFIG_QNAME.getNamespace().toString()));
374 final var metadata = operation.map(o -> leafMetadata(dataPath, o)).orElse(null);
376 if (lastChildOverride.isPresent()) {
377 // TODO do not transform this into result and then to xml, rework the whole pipeline to directly write
380 final var parentPath = dataPath.isEmpty() ? dataPath : dataPath.coerceParent();
381 var result = new NormalizedNodeResult();
382 try (var streamWriter = ImmutableNormalizedNodeStreamWriter.from(result)) {
383 try (var iidWriter = YangInstanceIdentifierWriter.open(streamWriter, ctx, parentPath);
384 var nnWriter = NormalizedNodeWriter.forStreamWriter(streamWriter)) {
385 nnWriter.write(lastChildOverride.get());
388 NetconfUtil.writeNormalizedNode(result.getResult(), metadata, new DOMResult(element), ctx, null);
390 NetconfUtil.writeNormalizedNode(dataPath, metadata, new DOMResult(element), ctx, null);
392 } catch (final IOException | XMLStreamException e) {
393 throw new IllegalStateException("Unable to serialize edit config content element for path " + dataPath, e);
396 return Builders.anyXmlBuilder().withNodeIdentifier(NETCONF_CONFIG_NODEID).withValue(new DOMSource(element))
400 private static NormalizedMetadata leafMetadata(final YangInstanceIdentifier path, final ModifyAction oper) {
401 final List<PathArgument> args = path.getPathArguments();
402 final Deque<Builder> builders = new ArrayDeque<>(args.size());
404 // Step one: open builders
405 for (PathArgument arg : args) {
406 builders.push(ImmutableNormalizedMetadata.builder().withIdentifier(arg));
409 // Step two: set the top builder's metadata
410 builders.peek().withAnnotation(NETCONF_OPERATION_QNAME_LEGACY, oper.toString().toLowerCase(Locale.US));
412 // Step three: build the tree
414 final ImmutableNormalizedMetadata currentMeta = builders.pop().build();
415 final Builder parent = builders.peek();
416 if (parent != null) {
417 parent.withChild(currentMeta);
424 public static DataContainerChild createEditConfigStructure(final EffectiveModelContext ctx,
425 final YangInstanceIdentifier dataPath, final Optional<ModifyAction> operation,
426 final Optional<NormalizedNode> lastChildOverride) {
427 return Builders.choiceBuilder().withNodeIdentifier(EDIT_CONTENT_NODEID)
428 .withChild(createEditConfigAnyxml(ctx, dataPath, operation, lastChildOverride)).build();
431 public static @NonNull Absolute toPath(final QName rpc) {
432 return Absolute.of(rpc);
435 public static Map.Entry<Instant, XmlElement> stripNotification(final NetconfMessage message) {
436 final XmlElement xmlElement = XmlElement.fromDomDocument(message.getDocument());
437 final List<XmlElement> childElements = xmlElement.getChildElements();
438 Preconditions.checkArgument(childElements.size() == 2, "Unable to parse notification %s, unexpected format."
439 + "\nExpected 2 childElements, actual childElements size is %s", message, childElements.size());
441 final XmlElement eventTimeElement;
442 final XmlElement notificationElement;
444 if (childElements.get(0).getName().equals(EVENT_TIME)) {
445 eventTimeElement = childElements.get(0);
446 notificationElement = childElements.get(1);
447 } else if (childElements.get(1).getName().equals(EVENT_TIME)) {
448 eventTimeElement = childElements.get(1);
449 notificationElement = childElements.get(0);
451 throw new IllegalArgumentException("Notification payload does not contain " + EVENT_TIME + " " + message);
455 return new SimpleEntry<>(
456 NetconfNotification.RFC3339_DATE_PARSER.apply(eventTimeElement.getTextContent()).toInstant(),
457 notificationElement);
458 } catch (final DocumentedException e) {
459 throw new IllegalArgumentException("Notification payload does not contain " + EVENT_TIME + " " + message,
461 } catch (final DateTimeParseException e) {
462 LOG.warn("Unable to parse event time from {}. Setting time to {}", eventTimeElement,
463 NetconfNotification.UNKNOWN_EVENT_TIME, e);
464 return new SimpleEntry<>(NetconfNotification.UNKNOWN_EVENT_TIME.toInstant(),
465 notificationElement);
469 public static DOMResult prepareDomResultForRpcRequest(final QName rpcQName, final MessageCounter counter) {
470 final Document document = XmlUtil.newDocument();
471 final Element rpcNS =
472 document.createElementNS(NETCONF_RPC_QNAME.getNamespace().toString(), NETCONF_RPC_QNAME.getLocalName());
474 rpcNS.setAttribute(MESSAGE_ID_ATTR, counter.getNewMessageId(MESSAGE_ID_PREFIX));
475 final Element elementNS = document.createElementNS(rpcQName.getNamespace().toString(), rpcQName.getLocalName());
476 rpcNS.appendChild(elementNS);
477 document.appendChild(rpcNS);
478 return new DOMResult(elementNS);
481 public static DOMResult prepareDomResultForActionRequest(final DataSchemaContextTree dataSchemaContextTree,
482 final DOMDataTreeIdentifier domDataTreeIdentifier, final MessageCounter counter, final QName action) {
483 final Document document = XmlUtil.newDocument();
484 final Element rpcNS =
485 document.createElementNS(NETCONF_RPC_QNAME.getNamespace().toString(), NETCONF_RPC_QNAME.getLocalName());
487 rpcNS.setAttribute(MESSAGE_ID_ATTR, counter.getNewMessageId(MESSAGE_ID_PREFIX));
489 final Element actionNS = document.createElementNS(NETCONF_ACTION_NAMESPACE.toString(), NETCONF_ACTION);
490 final DataSchemaContextNode<?> rootSchemaContextNode = dataSchemaContextTree.getRoot();
491 final Element actionData = prepareActionData(rootSchemaContextNode, actionNS,
492 domDataTreeIdentifier.getRootIdentifier().getPathArguments().iterator(), document);
494 final Element specificActionElement =
495 document.createElementNS(action.getNamespace().toString(), action.getLocalName());
496 actionData.appendChild(specificActionElement);
497 rpcNS.appendChild(actionNS);
498 document.appendChild(rpcNS);
499 return new DOMResult(specificActionElement);
502 private static Element prepareActionData(final DataSchemaContextNode<?> currentParentSchemaNode,
503 final Element actionNS, final Iterator<PathArgument> iterator, final Document document) {
504 if (iterator.hasNext()) {
505 final PathArgument next = iterator.next();
507 final DataSchemaContextNode<?> current = currentParentSchemaNode.getChild(next);
508 Preconditions.checkArgument(current != null, "Invalid input: schema for argument %s not found", next);
510 if (current.isMixin()) {
511 return prepareActionData(current, actionNS, iterator, document);
514 final QName actualNS = next.getNodeType();
515 final Element actualElement = document.createElementNS(actualNS.getNamespace().toString(),
516 actualNS.getLocalName());
517 if (next instanceof NodeWithValue) {
518 actualElement.setNodeValue(((NodeWithValue<?>) next).getValue().toString());
519 } else if (next instanceof NodeIdentifierWithPredicates) {
520 for (Entry<QName, Object> entry : ((NodeIdentifierWithPredicates) next).entrySet()) {
521 final Element entryElement = document.createElementNS(entry.getKey().getNamespace().toString(),
522 entry.getKey().getLocalName());
523 entryElement.setTextContent(entry.getValue().toString());
524 entryElement.setNodeValue(entry.getValue().toString());
525 actualElement.appendChild(entryElement);
528 actionNS.appendChild(actualElement);
529 return prepareActionData(current, actualElement, iterator, document);
535 public static void writeNormalizedOperationInput(final ContainerNode normalized, final DOMResult result,
536 final Absolute operationPath, final EffectiveModelContext baseNetconfCtx)
537 throws IOException, XMLStreamException {
538 final var stack = SchemaInferenceStack.of(baseNetconfCtx, operationPath);
539 stack.enterSchemaTree(YangConstants.operationInputQName(operationPath.lastNodeIdentifier().getModule()));
540 final var inputInference = stack.toSchemaTreeInference();
542 final XMLStreamWriter writer = NetconfUtil.XML_FACTORY.createXMLStreamWriter(result);
544 try (NormalizedNodeStreamWriter normalizedNodeStreamWriter =
545 XMLStreamNormalizedNodeStreamWriter.create(writer, inputInference)) {
546 try (SchemaOrderedNormalizedNodeWriter normalizedNodeWriter =
547 new SchemaOrderedNormalizedNodeWriter(normalizedNodeStreamWriter, inputInference)) {
548 final Collection<DataContainerChild> value = normalized.body();
549 normalizedNodeWriter.write(value);
550 normalizedNodeWriter.flush();
556 } catch (final XMLStreamException e) {
557 LOG.warn("Unable to close resource properly", e);
562 public static RpcResult<NetconfMessage> toRpcResult(final FailedNetconfMessage message) {
563 return RpcResultBuilder.<NetconfMessage>failed()
564 .withRpcError(toRpcError(new NetconfDocumentedException(message.getException().getMessage(),
565 ErrorType.APPLICATION, ErrorTag.MALFORMED_MESSAGE, ErrorSeverity.ERROR)))