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.client.mdsal.impl;
10 import static org.opendaylight.netconf.common.mdsal.NormalizedDataUtil.NETCONF_DATA_QNAME;
11 import static org.opendaylight.netconf.common.mdsal.NormalizedDataUtil.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;
17 import java.time.Instant;
18 import java.time.format.DateTimeParseException;
19 import java.util.ArrayDeque;
20 import java.util.Collection;
21 import java.util.Deque;
22 import java.util.Iterator;
23 import java.util.List;
24 import java.util.Locale;
26 import java.util.Map.Entry;
27 import java.util.Optional;
28 import javax.xml.stream.XMLStreamException;
29 import javax.xml.stream.XMLStreamWriter;
30 import javax.xml.transform.dom.DOMResult;
31 import javax.xml.transform.dom.DOMSource;
32 import org.eclipse.jdt.annotation.NonNull;
33 import org.opendaylight.mdsal.dom.api.DOMDataTreeIdentifier;
34 import org.opendaylight.netconf.api.DocumentedException;
35 import org.opendaylight.netconf.api.EffectiveOperation;
36 import org.opendaylight.netconf.api.NetconfDocumentedException;
37 import org.opendaylight.netconf.api.NetconfMessage;
38 import org.opendaylight.netconf.api.messages.NotificationMessage;
39 import org.opendaylight.netconf.api.xml.XmlElement;
40 import org.opendaylight.netconf.api.xml.XmlUtil;
41 import org.opendaylight.netconf.client.NetconfMessageUtil;
42 import org.opendaylight.netconf.common.mdsal.NormalizedDataUtil;
43 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netconf.base._1._0.rev110601.edit.config.input.EditContent;
44 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netconf.notification._1._0.rev080714.CreateSubscriptionInput;
45 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.monitoring.rev101004.NetconfState;
46 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.notifications.rev120206.NetconfCapabilityChange;
47 import org.opendaylight.yangtools.rfc7952.data.api.NormalizedMetadata;
48 import org.opendaylight.yangtools.rfc7952.data.util.ImmutableNormalizedMetadata;
49 import org.opendaylight.yangtools.rfc7952.data.util.ImmutableNormalizedMetadata.Builder;
50 import org.opendaylight.yangtools.yang.common.ErrorSeverity;
51 import org.opendaylight.yangtools.yang.common.ErrorTag;
52 import org.opendaylight.yangtools.yang.common.ErrorType;
53 import org.opendaylight.yangtools.yang.common.QName;
54 import org.opendaylight.yangtools.yang.common.XMLNamespace;
55 import org.opendaylight.yangtools.yang.common.YangConstants;
56 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
57 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
58 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
59 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeWithValue;
60 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
61 import org.opendaylight.yangtools.yang.data.api.schema.AnyxmlNode;
62 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
63 import org.opendaylight.yangtools.yang.data.api.schema.DOMSourceAnyxmlNode;
64 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
65 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
66 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
67 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeWriter;
68 import org.opendaylight.yangtools.yang.data.api.schema.stream.YangInstanceIdentifierWriter;
69 import org.opendaylight.yangtools.yang.data.codec.xml.XMLStreamNormalizedNodeStreamWriter;
70 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
71 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNormalizedNodeStreamWriter;
72 import org.opendaylight.yangtools.yang.data.impl.schema.NormalizedNodeResult;
73 import org.opendaylight.yangtools.yang.data.impl.schema.SchemaOrderedNormalizedNodeWriter;
74 import org.opendaylight.yangtools.yang.data.util.DataSchemaContextNode;
75 import org.opendaylight.yangtools.yang.data.util.DataSchemaContextTree;
76 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
77 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier.Absolute;
78 import org.opendaylight.yangtools.yang.model.util.SchemaInferenceStack;
79 import org.slf4j.Logger;
80 import org.slf4j.LoggerFactory;
81 import org.w3c.dom.Document;
82 import org.w3c.dom.Element;
84 public final class NetconfMessageTransformUtil {
85 private static final Logger LOG = LoggerFactory.getLogger(NetconfMessageTransformUtil.class);
87 public static final String MESSAGE_ID_PREFIX = "m";
88 public static final String MESSAGE_ID_ATTR = "message-id";
90 public static final @NonNull QName CREATE_SUBSCRIPTION_RPC_QNAME =
91 QName.create(CreateSubscriptionInput.QNAME, "create-subscription").intern();
92 private static final String SUBTREE = "subtree";
94 // Blank document used for creation of new DOM nodes
95 private static final Document BLANK_DOCUMENT = XmlUtil.newDocument();
96 public static final String EVENT_TIME = "eventTime";
98 private NetconfMessageTransformUtil() {
102 public static final @NonNull QName IETF_NETCONF_MONITORING =
103 QName.create(NetconfState.QNAME, "ietf-netconf-monitoring").intern();
104 public static final @NonNull QName GET_DATA_QNAME = QName.create(IETF_NETCONF_MONITORING, "data").intern();
105 public static final @NonNull QName GET_SCHEMA_QNAME = QName.create(IETF_NETCONF_MONITORING, "get-schema").intern();
106 public static final @NonNull QName IETF_NETCONF_MONITORING_SCHEMA_FORMAT =
107 QName.create(IETF_NETCONF_MONITORING, "format").intern();
108 public static final @NonNull QName IETF_NETCONF_MONITORING_SCHEMA_LOCATION =
109 QName.create(IETF_NETCONF_MONITORING, "location").intern();
110 public static final @NonNull QName IETF_NETCONF_MONITORING_SCHEMA_IDENTIFIER =
111 QName.create(IETF_NETCONF_MONITORING, "identifier").intern();
112 public static final @NonNull QName IETF_NETCONF_MONITORING_SCHEMA_VERSION =
113 QName.create(IETF_NETCONF_MONITORING, "version").intern();
114 public static final @NonNull QName IETF_NETCONF_MONITORING_SCHEMA_NAMESPACE =
115 QName.create(IETF_NETCONF_MONITORING, "namespace").intern();
117 public static final @NonNull QName IETF_NETCONF_NOTIFICATIONS =
118 QName.create(NetconfCapabilityChange.QNAME, "ietf-netconf-notifications").intern();
120 public static final XMLNamespace NETCONF_URI = NETCONF_QNAME.getNamespace();
122 public static final @NonNull NodeIdentifier NETCONF_DATA_NODEID = NodeIdentifier.create(NETCONF_DATA_QNAME);
124 public static final @NonNull QName NETCONF_RPC_REPLY_QNAME = QName.create(NETCONF_QNAME, "rpc-reply").intern();
125 public static final @NonNull NodeIdentifier NETCONF_RPC_REPLY_NODEID =
126 NodeIdentifier.create(NETCONF_RPC_REPLY_QNAME);
128 public static final @NonNull QName NETCONF_OK_QNAME = QName.create(NETCONF_QNAME, "ok").intern();
129 public static final @NonNull QName NETCONF_ERROR_OPTION_QNAME =
130 QName.create(NETCONF_QNAME, "error-option").intern();
131 public static final @NonNull NodeIdentifier NETCONF_ERROR_OPTION_NODEID =
132 NodeIdentifier.create(NETCONF_ERROR_OPTION_QNAME);
133 public static final @NonNull QName NETCONF_RUNNING_QNAME = QName.create(NETCONF_QNAME, "running").intern();
134 public static final @NonNull NodeIdentifier NETCONF_RUNNING_NODEID = NodeIdentifier.create(NETCONF_RUNNING_QNAME);
135 public static final @NonNull QName NETCONF_SOURCE_QNAME = QName.create(NETCONF_QNAME, "source").intern();
136 public static final @NonNull NodeIdentifier NETCONF_SOURCE_NODEID = NodeIdentifier.create(NETCONF_SOURCE_QNAME);
137 public static final @NonNull QName NETCONF_CANDIDATE_QNAME = QName.create(NETCONF_QNAME, "candidate").intern();
138 public static final @NonNull NodeIdentifier NETCONF_CANDIDATE_NODEID =
139 NodeIdentifier.create(NETCONF_CANDIDATE_QNAME);
140 public static final @NonNull QName NETCONF_TARGET_QNAME = QName.create(NETCONF_QNAME, "target").intern();
141 public static final @NonNull NodeIdentifier NETCONF_TARGET_NODEID = NodeIdentifier.create(NETCONF_TARGET_QNAME);
142 public static final @NonNull QName NETCONF_CONFIG_QNAME = QName.create(NETCONF_QNAME, "config").intern();
143 public static final @NonNull NodeIdentifier NETCONF_CONFIG_NODEID = NodeIdentifier.create(NETCONF_CONFIG_QNAME);
145 public static final @NonNull QName NETCONF_COMMIT_QNAME = QName.create(NETCONF_QNAME, "commit").intern();
146 public static final @NonNull Absolute NETCONF_COMMIT_PATH = toPath(NETCONF_COMMIT_QNAME);
147 public static final @NonNull QName NETCONF_VALIDATE_QNAME = QName.create(NETCONF_QNAME, "validate").intern();
148 public static final @NonNull NodeIdentifier NETCONF_VALIDATE_NODEID = NodeIdentifier.create(NETCONF_VALIDATE_QNAME);
149 public static final @NonNull Absolute NETCONF_VALIDATE_PATH = toPath(NETCONF_VALIDATE_QNAME);
150 public static final @NonNull QName NETCONF_COPY_CONFIG_QNAME = QName.create(NETCONF_QNAME, "copy-config").intern();
151 public static final @NonNull NodeIdentifier NETCONF_COPY_CONFIG_NODEID =
152 NodeIdentifier.create(NETCONF_COPY_CONFIG_QNAME);
153 public static final @NonNull Absolute NETCONF_COPY_CONFIG_PATH = toPath(NETCONF_COPY_CONFIG_QNAME);
155 public static final @NonNull QName NETCONF_OPERATION_QNAME = QName.create(NETCONF_QNAME, "operation").intern();
156 private static final @NonNull QName NETCONF_OPERATION_QNAME_LEGACY =
157 NETCONF_OPERATION_QNAME.withoutRevision().intern();
158 public static final @NonNull QName NETCONF_DEFAULT_OPERATION_QNAME =
159 QName.create(NETCONF_OPERATION_QNAME, "default-operation").intern();
160 public static final @NonNull NodeIdentifier NETCONF_DEFAULT_OPERATION_NODEID =
161 NodeIdentifier.create(NETCONF_DEFAULT_OPERATION_QNAME);
162 public static final @NonNull QName NETCONF_EDIT_CONFIG_QNAME = QName.create(NETCONF_QNAME, "edit-config").intern();
163 public static final @NonNull NodeIdentifier NETCONF_EDIT_CONFIG_NODEID =
164 NodeIdentifier.create(NETCONF_EDIT_CONFIG_QNAME);
165 public static final @NonNull Absolute NETCONF_EDIT_CONFIG_PATH = toPath(NETCONF_EDIT_CONFIG_QNAME);
166 public static final @NonNull QName NETCONF_GET_CONFIG_QNAME = QName.create(NETCONF_QNAME, "get-config");
167 public static final @NonNull NodeIdentifier NETCONF_GET_CONFIG_NODEID =
168 NodeIdentifier.create(NETCONF_GET_CONFIG_QNAME);
169 public static final @NonNull Absolute NETCONF_GET_CONFIG_PATH = toPath(NETCONF_GET_CONFIG_QNAME);
170 public static final @NonNull QName NETCONF_DISCARD_CHANGES_QNAME = QName.create(NETCONF_QNAME, "discard-changes");
171 public static final @NonNull Absolute NETCONF_DISCARD_CHANGES_PATH = toPath(NETCONF_DISCARD_CHANGES_QNAME);
172 public static final @NonNull QName NETCONF_TYPE_QNAME = QName.create(NETCONF_QNAME, "type").intern();
173 public static final @NonNull QName NETCONF_FILTER_QNAME = QName.create(NETCONF_QNAME, "filter").intern();
174 public static final @NonNull QName NETCONF_GET_QNAME = QName.create(NETCONF_QNAME, "get").intern();
175 public static final @NonNull NodeIdentifier NETCONF_GET_NODEID = NodeIdentifier.create(NETCONF_GET_QNAME);
176 public static final @NonNull Absolute NETCONF_GET_PATH = toPath(NETCONF_GET_QNAME);
177 public static final @NonNull QName NETCONF_RPC_QNAME = QName.create(NETCONF_QNAME, "rpc").intern();
179 public static final @NonNull QName NETCONF_LOCK_QNAME = QName.create(NETCONF_QNAME, "lock").intern();
180 public static final @NonNull NodeIdentifier NETCONF_LOCK_NODEID = NodeIdentifier.create(NETCONF_LOCK_QNAME);
181 public static final @NonNull Absolute NETCONF_LOCK_PATH = toPath(NETCONF_LOCK_QNAME);
182 public static final @NonNull QName NETCONF_UNLOCK_QNAME = QName.create(NETCONF_QNAME, "unlock").intern();
183 public static final @NonNull NodeIdentifier NETCONF_UNLOCK_NODEID = NodeIdentifier.create(NETCONF_UNLOCK_QNAME);
184 public static final @NonNull Absolute NETCONF_UNLOCK_PATH = toPath(NETCONF_UNLOCK_QNAME);
186 public static final @NonNull NodeIdentifier EDIT_CONTENT_NODEID = NodeIdentifier.create(EditContent.QNAME);
188 // Discard changes message
189 public static final @NonNull ContainerNode DISCARD_CHANGES_RPC_CONTENT = Builders.containerBuilder()
190 .withNodeIdentifier(NodeIdentifier.create(NETCONF_DISCARD_CHANGES_QNAME)).build();
192 // Commit changes message
193 public static final @NonNull ContainerNode COMMIT_RPC_CONTENT = Builders.containerBuilder()
194 .withNodeIdentifier(NodeIdentifier.create(NETCONF_COMMIT_QNAME)).build();
197 public static final @NonNull ContainerNode GET_RPC_CONTENT = Builders.containerBuilder()
198 .withNodeIdentifier(NETCONF_GET_NODEID).build();
200 // Create-subscription changes message
201 public static final @NonNull ContainerNode CREATE_SUBSCRIPTION_RPC_CONTENT = Builders.containerBuilder()
202 .withNodeIdentifier(NodeIdentifier.create(CREATE_SUBSCRIPTION_RPC_QNAME)).build();
204 public static final @NonNull Absolute CREATE_SUBSCRIPTION_RPC_PATH = toPath(CREATE_SUBSCRIPTION_RPC_QNAME);
206 public static final @NonNull NodeIdentifier NETCONF_FILTER_NODEID = NodeIdentifier.create(NETCONF_FILTER_QNAME);
208 public static final @NonNull AnyxmlNode<?> EMPTY_FILTER = buildFilterStructure(getNetconfFilterElement());
211 * Creation of the subtree filter structure using {@link YangInstanceIdentifier} path.
213 * @param identifier parent path / query
214 * @param ctx mountpoint schema context
215 * @return created DOM structure with subtree filter
217 public static AnyxmlNode<?> toFilterStructure(final YangInstanceIdentifier identifier,
218 final EffectiveModelContext ctx) {
219 final Element element = getNetconfFilterElement();
221 NormalizedDataUtil.writeFilter(identifier, new DOMResult(element), ctx, null);
222 } catch (IOException | XMLStreamException e) {
223 throw new IllegalStateException("Unable to serialize filter element for path " + identifier, e);
225 return buildFilterStructure(element);
229 * Creation of the subtree filter structure using list of parent {@link YangInstanceIdentifier}
230 * and specific selection fields. Field paths are relative to parent query path.
232 * @param fieldsFilters list of: parent path and selection fields
233 * @param ctx mountpoint schema context
234 * @return created DOM structure with subtree filter
236 public static AnyxmlNode<?> toFilterStructure(final List<FieldsFilter> fieldsFilters,
237 final EffectiveModelContext ctx) {
238 Preconditions.checkState(!fieldsFilters.isEmpty(), "An empty list of subtree filters is not allowed");
239 final Element element = getNetconfFilterElement();
241 for (final FieldsFilter filter : fieldsFilters) {
243 NormalizedDataUtil.writeFilter(filter.path(), new DOMResult(element), ctx, null, filter.fields());
244 } catch (IOException | XMLStreamException e) {
245 throw new IllegalStateException(String.format(
246 "Unable to serialize filter element for path %s with fields: %s",
247 filter.path(), filter.fields()), e);
250 return buildFilterStructure(element);
253 private static Element getNetconfFilterElement() {
254 final Element element = XmlUtil.createElement(BLANK_DOCUMENT, NETCONF_FILTER_QNAME.getLocalName(),
255 Optional.of(NETCONF_FILTER_QNAME.getNamespace().toString()));
256 element.setAttributeNS(NETCONF_FILTER_QNAME.getNamespace().toString(), NETCONF_TYPE_QNAME.getLocalName(),
261 private static AnyxmlNode<?> buildFilterStructure(final Element element) {
262 return Builders.anyXmlBuilder()
263 .withNodeIdentifier(NETCONF_FILTER_NODEID)
264 .withValue(new DOMSource(element))
268 public static void checkValidReply(final NetconfMessage input, final NetconfMessage output)
269 throws NetconfDocumentedException {
270 final String inputMsgId = input.getDocument().getDocumentElement().getAttribute(MESSAGE_ID_ATTR);
271 final String outputMsgId = output.getDocument().getDocumentElement().getAttribute(MESSAGE_ID_ATTR);
273 if (!inputMsgId.equals(outputMsgId)) {
274 throw new NetconfDocumentedException("Response message contained unknown \"message-id\"", null,
275 ErrorType.PROTOCOL, ErrorTag.BAD_ATTRIBUTE, ErrorSeverity.ERROR,
276 ImmutableMap.of("actual-message-id", outputMsgId, "expected-message-id", inputMsgId));
280 public static void checkSuccessReply(final NetconfMessage output) throws NetconfDocumentedException {
281 if (NetconfMessageUtil.isErrorMessage(output)) {
282 throw NetconfDocumentedException.fromXMLDocument(output.getDocument());
286 public static NodeIdentifier toId(final PathArgument arg) {
287 return arg instanceof NodeIdentifier nodeId ? nodeId : toId(arg.getNodeType());
290 public static NodeIdentifier toId(final QName nodeType) {
291 return new NodeIdentifier(nodeType);
294 public static Element getDataSubtree(final Document doc) {
295 return (Element) doc.getElementsByTagNameNS(NETCONF_URI.toString(), "data").item(0);
298 public static boolean isDataRetrievalOperation(final QName rpc) {
299 return NETCONF_URI.equals(rpc.getNamespace())
300 && (NETCONF_GET_CONFIG_QNAME.getLocalName().equals(rpc.getLocalName())
301 || NETCONF_GET_QNAME.getLocalName().equals(rpc.getLocalName()));
305 public static @NonNull ContainerNode wrap(final QName name, final DataContainerChild... node) {
306 return wrap(toId(name), node);
309 public static @NonNull ContainerNode wrap(final NodeIdentifier name, final DataContainerChild... node) {
310 return Builders.containerBuilder().withNodeIdentifier(name).withValue(ImmutableList.copyOf(node)).build();
314 * Create edit-config structure to invoke {@code operation} with {@code lastChildOverride} data on {@code dataPath}.
316 * @param ctx {@link EffectiveModelContext} device's model context
317 * @param dataPath {@link YangInstanceIdentifier} path to data in device's data-store
318 * @param operation Optional of {@link EffectiveOperation} action to be invoked
319 * @param lastChildOverride Optional of {@code NormalizedNode} data on which action will be invoked
320 * @return {@link DOMSourceAnyxmlNode} containing edit-config structure
322 public static DOMSourceAnyxmlNode createEditConfigAnyxml(
323 final EffectiveModelContext ctx, final YangInstanceIdentifier dataPath,
324 final Optional<EffectiveOperation> operation, final Optional<NormalizedNode> lastChildOverride) {
325 if (dataPath.isEmpty()) {
326 final var override = lastChildOverride.orElseThrow(() -> new IllegalArgumentException(
327 "Data has to be present when creating structure for top level element"));
328 Preconditions.checkArgument(override instanceof DataContainerChild,
329 "Data has to be either container or a list node when creating structure for top level element, "
330 + "but was: %s", override);
333 final var element = XmlUtil.createElement(BLANK_DOCUMENT, NETCONF_CONFIG_QNAME.getLocalName(),
334 Optional.of(NETCONF_CONFIG_QNAME.getNamespace().toString()));
335 final var metadata = operation.map(o -> leafMetadata(dataPath, o)).orElse(null);
337 if (lastChildOverride.isPresent()) {
338 // TODO do not transform this into result and then to xml, rework the whole pipeline to directly write
341 final var parentPath = dataPath.isEmpty() ? dataPath : dataPath.coerceParent();
342 var result = new NormalizedNodeResult();
343 try (var streamWriter = ImmutableNormalizedNodeStreamWriter.from(result)) {
344 try (var iidWriter = YangInstanceIdentifierWriter.open(streamWriter, ctx, parentPath);
345 var nnWriter = NormalizedNodeWriter.forStreamWriter(streamWriter)) {
346 nnWriter.write(lastChildOverride.orElseThrow());
349 NormalizedDataUtil.writeNormalizedNode(result.getResult(), metadata, new DOMResult(element), ctx, null);
351 NormalizedDataUtil.writeNormalizedNode(dataPath, metadata, new DOMResult(element), ctx, null);
353 } catch (final IOException | XMLStreamException e) {
354 throw new IllegalStateException("Unable to serialize edit config content element for path " + dataPath, e);
357 return Builders.anyXmlBuilder().withNodeIdentifier(NETCONF_CONFIG_NODEID).withValue(new DOMSource(element))
361 private static NormalizedMetadata leafMetadata(final YangInstanceIdentifier path, final EffectiveOperation oper) {
362 final List<PathArgument> args = path.getPathArguments();
363 final Deque<Builder> builders = new ArrayDeque<>(args.size());
365 // Step one: open builders
366 for (PathArgument arg : args) {
367 builders.push(ImmutableNormalizedMetadata.builder().withIdentifier(arg));
370 // Step two: set the top builder's metadata
371 builders.peek().withAnnotation(NETCONF_OPERATION_QNAME_LEGACY, oper.toString().toLowerCase(Locale.US));
373 // Step three: build the tree
375 final ImmutableNormalizedMetadata currentMeta = builders.pop().build();
376 final Builder parent = builders.peek();
377 if (parent != null) {
378 parent.withChild(currentMeta);
385 public static DataContainerChild createEditConfigStructure(final EffectiveModelContext ctx,
386 final YangInstanceIdentifier dataPath, final Optional<EffectiveOperation> operation,
387 final Optional<NormalizedNode> lastChildOverride) {
388 return Builders.choiceBuilder().withNodeIdentifier(EDIT_CONTENT_NODEID)
389 .withChild(createEditConfigAnyxml(ctx, dataPath, operation, lastChildOverride)).build();
392 public static @NonNull Absolute toPath(final QName rpc) {
393 return Absolute.of(rpc);
396 public static Map.Entry<Instant, XmlElement> stripNotification(final NetconfMessage message) {
397 final XmlElement xmlElement = XmlElement.fromDomDocument(message.getDocument());
398 final List<XmlElement> childElements = xmlElement.getChildElements();
399 Preconditions.checkArgument(childElements.size() == 2, "Unable to parse notification %s, unexpected format."
400 + "\nExpected 2 childElements, actual childElements size is %s", message, childElements.size());
402 final XmlElement eventTimeElement;
403 final XmlElement notificationElement;
405 if (childElements.get(0).getName().equals(EVENT_TIME)) {
406 eventTimeElement = childElements.get(0);
407 notificationElement = childElements.get(1);
408 } else if (childElements.get(1).getName().equals(EVENT_TIME)) {
409 eventTimeElement = childElements.get(1);
410 notificationElement = childElements.get(0);
412 throw new IllegalArgumentException("Notification payload does not contain " + EVENT_TIME + " " + message);
417 NotificationMessage.RFC3339_DATE_PARSER.apply(eventTimeElement.getTextContent()),
418 notificationElement);
419 } catch (final DocumentedException e) {
420 throw new IllegalArgumentException("Notification payload does not contain " + EVENT_TIME + " " + message,
422 } catch (final DateTimeParseException e) {
423 LOG.warn("Unable to parse event time from {}. Setting time to {}", eventTimeElement,
424 NotificationMessage.UNKNOWN_EVENT_TIME, e);
425 return Map.entry(NotificationMessage.UNKNOWN_EVENT_TIME, notificationElement);
429 public static DOMResult prepareDomResultForRpcRequest(final QName rpcQName, final MessageCounter counter) {
430 final Document document = XmlUtil.newDocument();
431 final Element rpcNS =
432 document.createElementNS(NETCONF_RPC_QNAME.getNamespace().toString(), NETCONF_RPC_QNAME.getLocalName());
434 rpcNS.setAttribute(MESSAGE_ID_ATTR, counter.getNewMessageId(MESSAGE_ID_PREFIX));
435 final Element elementNS = document.createElementNS(rpcQName.getNamespace().toString(), rpcQName.getLocalName());
436 rpcNS.appendChild(elementNS);
437 document.appendChild(rpcNS);
438 return new DOMResult(elementNS);
441 public static DOMResult prepareDomResultForActionRequest(final DataSchemaContextTree dataSchemaContextTree,
442 final DOMDataTreeIdentifier domDataTreeIdentifier, final MessageCounter counter, final QName action) {
443 final Document document = XmlUtil.newDocument();
444 final Element rpcNS =
445 document.createElementNS(NETCONF_RPC_QNAME.getNamespace().toString(), NETCONF_RPC_QNAME.getLocalName());
447 rpcNS.setAttribute(MESSAGE_ID_ATTR, counter.getNewMessageId(MESSAGE_ID_PREFIX));
449 final Element actionNS = document.createElementNS(YangConstants.RFC6020_YANG_NAMESPACE_STRING, "action");
450 final DataSchemaContextNode<?> rootSchemaContextNode = dataSchemaContextTree.getRoot();
451 final Element actionData = prepareActionData(rootSchemaContextNode, actionNS,
452 domDataTreeIdentifier.getRootIdentifier().getPathArguments().iterator(), document);
454 final Element specificActionElement =
455 document.createElementNS(action.getNamespace().toString(), action.getLocalName());
456 actionData.appendChild(specificActionElement);
457 rpcNS.appendChild(actionNS);
458 document.appendChild(rpcNS);
459 return new DOMResult(specificActionElement);
462 private static Element prepareActionData(final DataSchemaContextNode<?> currentParentSchemaNode,
463 final Element actionNS, final Iterator<PathArgument> iterator, final Document document) {
464 if (iterator.hasNext()) {
465 final PathArgument next = iterator.next();
467 final DataSchemaContextNode<?> current = currentParentSchemaNode.getChild(next);
468 Preconditions.checkArgument(current != null, "Invalid input: schema for argument %s not found", next);
470 if (current.isMixin()) {
471 return prepareActionData(current, actionNS, iterator, document);
474 final QName actualNS = next.getNodeType();
475 final Element actualElement = document.createElementNS(actualNS.getNamespace().toString(),
476 actualNS.getLocalName());
477 if (next instanceof NodeWithValue) {
478 actualElement.setNodeValue(((NodeWithValue<?>) next).getValue().toString());
479 } else if (next instanceof NodeIdentifierWithPredicates) {
480 for (Entry<QName, Object> entry : ((NodeIdentifierWithPredicates) next).entrySet()) {
481 final Element entryElement = document.createElementNS(entry.getKey().getNamespace().toString(),
482 entry.getKey().getLocalName());
483 entryElement.setTextContent(entry.getValue().toString());
484 entryElement.setNodeValue(entry.getValue().toString());
485 actualElement.appendChild(entryElement);
488 actionNS.appendChild(actualElement);
489 return prepareActionData(current, actualElement, iterator, document);
495 public static void writeNormalizedOperationInput(final ContainerNode normalized, final DOMResult result,
496 final Absolute operationPath, final EffectiveModelContext baseNetconfCtx)
497 throws IOException, XMLStreamException {
498 final var stack = SchemaInferenceStack.of(baseNetconfCtx, operationPath);
499 stack.enterSchemaTree(YangConstants.operationInputQName(operationPath.lastNodeIdentifier().getModule()));
500 final var inputInference = stack.toSchemaTreeInference();
502 final XMLStreamWriter writer = NormalizedDataUtil.XML_FACTORY.createXMLStreamWriter(result);
504 try (NormalizedNodeStreamWriter normalizedNodeStreamWriter =
505 XMLStreamNormalizedNodeStreamWriter.create(writer, inputInference)) {
506 try (SchemaOrderedNormalizedNodeWriter normalizedNodeWriter =
507 new SchemaOrderedNormalizedNodeWriter(normalizedNodeStreamWriter, inputInference)) {
508 final Collection<DataContainerChild> value = normalized.body();
509 normalizedNodeWriter.write(value);
510 normalizedNodeWriter.flush();
516 } catch (final XMLStreamException e) {
517 LOG.warn("Unable to close resource properly", e);