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 com.google.common.base.Preconditions;
11 import com.google.common.collect.ImmutableList;
12 import com.google.common.collect.ImmutableMap;
13 import com.google.common.collect.Iterables;
14 import java.io.IOException;
16 import java.time.Instant;
17 import java.time.format.DateTimeParseException;
18 import java.util.AbstractMap.SimpleEntry;
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.opendaylight.mdsal.dom.api.DOMDataTreeIdentifier;
33 import org.opendaylight.netconf.api.DocumentedException;
34 import org.opendaylight.netconf.api.FailedNetconfMessage;
35 import org.opendaylight.netconf.api.ModifyAction;
36 import org.opendaylight.netconf.api.NetconfDocumentedException;
37 import org.opendaylight.netconf.api.NetconfMessage;
38 import org.opendaylight.netconf.api.xml.XmlElement;
39 import org.opendaylight.netconf.api.xml.XmlUtil;
40 import org.opendaylight.netconf.notifications.NetconfNotification;
41 import org.opendaylight.netconf.sal.connect.util.MessageCounter;
42 import org.opendaylight.netconf.util.NetconfUtil;
43 import org.opendaylight.netconf.util.messages.NetconfMessageUtil;
44 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netconf.base._1._0.rev110601.edit.config.input.EditContent;
45 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netconf.notification._1._0.rev080714.CreateSubscriptionInput;
46 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.monitoring.rev101004.NetconfState;
47 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.notifications.rev120206.NetconfCapabilityChange;
48 import org.opendaylight.yangtools.rfc7952.data.api.NormalizedMetadata;
49 import org.opendaylight.yangtools.rfc7952.data.util.ImmutableNormalizedMetadata;
50 import org.opendaylight.yangtools.rfc7952.data.util.ImmutableNormalizedMetadata.Builder;
51 import org.opendaylight.yangtools.yang.common.QName;
52 import org.opendaylight.yangtools.yang.common.RpcError;
53 import org.opendaylight.yangtools.yang.common.RpcError.ErrorSeverity;
54 import org.opendaylight.yangtools.yang.common.RpcResult;
55 import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
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.DataContainerChild;
64 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
65 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNodeContainer;
66 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
67 import org.opendaylight.yangtools.yang.data.codec.xml.XMLStreamNormalizedNodeStreamWriter;
68 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
69 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
70 import org.opendaylight.yangtools.yang.data.impl.schema.SchemaOrderedNormalizedNodeWriter;
71 import org.opendaylight.yangtools.yang.data.util.DataSchemaContextNode;
72 import org.opendaylight.yangtools.yang.data.util.DataSchemaContextTree;
73 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
74 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
75 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
76 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
77 import org.slf4j.Logger;
78 import org.slf4j.LoggerFactory;
79 import org.w3c.dom.Document;
80 import org.w3c.dom.Element;
82 public final class NetconfMessageTransformUtil {
84 private static final Logger LOG = LoggerFactory.getLogger(NetconfMessageTransformUtil.class);
86 public static final String MESSAGE_ID_PREFIX = "m";
87 public static final String MESSAGE_ID_ATTR = "message-id";
89 public static final QName CREATE_SUBSCRIPTION_RPC_QNAME =
90 QName.create(CreateSubscriptionInput.QNAME, "create-subscription").intern();
91 private static final String SUBTREE = "subtree";
93 // Blank document used for creation of new DOM nodes
94 private static final Document BLANK_DOCUMENT = XmlUtil.newDocument();
95 public static final String EVENT_TIME = "eventTime";
97 private NetconfMessageTransformUtil() {}
99 public static final QName IETF_NETCONF_MONITORING =
100 QName.create(NetconfState.QNAME, "ietf-netconf-monitoring").intern();
101 public static final QName GET_DATA_QNAME = QName.create(IETF_NETCONF_MONITORING, "data").intern();
102 public static final QName GET_SCHEMA_QNAME = QName.create(IETF_NETCONF_MONITORING, "get-schema").intern();
103 public static final QName IETF_NETCONF_MONITORING_SCHEMA_FORMAT =
104 QName.create(IETF_NETCONF_MONITORING, "format").intern();
105 public static final QName IETF_NETCONF_MONITORING_SCHEMA_LOCATION =
106 QName.create(IETF_NETCONF_MONITORING, "location").intern();
107 public static final QName IETF_NETCONF_MONITORING_SCHEMA_IDENTIFIER =
108 QName.create(IETF_NETCONF_MONITORING, "identifier").intern();
109 public static final QName IETF_NETCONF_MONITORING_SCHEMA_VERSION =
110 QName.create(IETF_NETCONF_MONITORING, "version").intern();
111 public static final QName IETF_NETCONF_MONITORING_SCHEMA_NAMESPACE =
112 QName.create(IETF_NETCONF_MONITORING, "namespace").intern();
114 public static final QName IETF_NETCONF_NOTIFICATIONS =
115 QName.create(NetconfCapabilityChange.QNAME, "ietf-netconf-notifications").intern();
117 public static final QName NETCONF_QNAME =
118 QName.create("urn:ietf:params:xml:ns:netconf:base:1.0", "2011-06-01", "netconf").intern();
119 public static final URI NETCONF_URI = NETCONF_QNAME.getNamespace();
121 public static final QName NETCONF_DATA_QNAME = QName.create(NETCONF_QNAME, "data").intern();
122 public static final NodeIdentifier NETCONF_DATA_NODEID = NodeIdentifier.create(NETCONF_DATA_QNAME);
124 public static final QName NETCONF_RPC_REPLY_QNAME = QName.create(NETCONF_QNAME, "rpc-reply").intern();
125 public static final NodeIdentifier NETCONF_RPC_REPLY_NODEID = NodeIdentifier.create(NETCONF_RPC_REPLY_QNAME);
127 public static final QName NETCONF_OK_QNAME = QName.create(NETCONF_QNAME, "ok").intern();
128 public static final QName NETCONF_ERROR_OPTION_QNAME = QName.create(NETCONF_QNAME, "error-option").intern();
129 public static final NodeIdentifier NETCONF_ERROR_OPTION_NODEID = NodeIdentifier.create(NETCONF_ERROR_OPTION_QNAME);
130 public static final QName NETCONF_RUNNING_QNAME = QName.create(NETCONF_QNAME, "running").intern();
131 public static final QName NETCONF_SOURCE_QNAME = QName.create(NETCONF_QNAME, "source").intern();
132 public static final NodeIdentifier NETCONF_SOURCE_NODEID = NodeIdentifier.create(NETCONF_SOURCE_QNAME);
133 public static final QName NETCONF_CANDIDATE_QNAME = QName.create(NETCONF_QNAME, "candidate").intern();
134 public static final QName NETCONF_TARGET_QNAME = QName.create(NETCONF_QNAME, "target").intern();
135 public static final NodeIdentifier NETCONF_TARGET_NODEID = NodeIdentifier.create(NETCONF_TARGET_QNAME);
136 public static final QName NETCONF_CONFIG_QNAME = QName.create(NETCONF_QNAME, "config").intern();
137 public static final NodeIdentifier NETCONF_CONFIG_NODEID = NodeIdentifier.create(NETCONF_CONFIG_QNAME);
139 public static final QName NETCONF_COMMIT_QNAME = QName.create(NETCONF_QNAME, "commit").intern();
140 public static final SchemaPath NETCONF_COMMIT_PATH = toPath(NETCONF_COMMIT_QNAME);
141 public static final QName NETCONF_VALIDATE_QNAME = QName.create(NETCONF_QNAME, "validate").intern();
142 public static final NodeIdentifier NETCONF_VALIDATE_NODEID = NodeIdentifier.create(NETCONF_VALIDATE_QNAME);
143 public static final SchemaPath NETCONF_VALIDATE_PATH = toPath(NETCONF_VALIDATE_QNAME);
144 public static final QName NETCONF_COPY_CONFIG_QNAME = QName.create(NETCONF_QNAME, "copy-config").intern();
145 public static final NodeIdentifier NETCONF_COPY_CONFIG_NODEID = NodeIdentifier.create(NETCONF_COPY_CONFIG_QNAME);
146 public static final SchemaPath NETCONF_COPY_CONFIG_PATH = toPath(NETCONF_COPY_CONFIG_QNAME);
148 public static final QName NETCONF_OPERATION_QNAME = QName.create(NETCONF_QNAME, "operation").intern();
149 private static final QName NETCONF_OPERATION_QNAME_LEGACY = NETCONF_OPERATION_QNAME.withoutRevision().intern();
150 public static final QName NETCONF_DEFAULT_OPERATION_QNAME =
151 QName.create(NETCONF_OPERATION_QNAME, "default-operation").intern();
152 public static final NodeIdentifier NETCONF_DEFAULT_OPERATION_NODEID =
153 NodeIdentifier.create(NETCONF_DEFAULT_OPERATION_QNAME);
154 public static final QName NETCONF_EDIT_CONFIG_QNAME = QName.create(NETCONF_QNAME, "edit-config").intern();
155 public static final NodeIdentifier NETCONF_EDIT_CONFIG_NODEID = NodeIdentifier.create(NETCONF_EDIT_CONFIG_QNAME);
156 public static final SchemaPath NETCONF_EDIT_CONFIG_PATH = toPath(NETCONF_EDIT_CONFIG_QNAME);
157 public static final QName NETCONF_GET_CONFIG_QNAME = QName.create(NETCONF_QNAME, "get-config");
158 public static final NodeIdentifier NETCONF_GET_CONFIG_NODEID = NodeIdentifier.create(NETCONF_GET_CONFIG_QNAME);
159 public static final SchemaPath NETCONF_GET_CONFIG_PATH = toPath(NETCONF_GET_CONFIG_QNAME);
160 public static final QName NETCONF_DISCARD_CHANGES_QNAME = QName.create(NETCONF_QNAME, "discard-changes");
161 public static final SchemaPath NETCONF_DISCARD_CHANGES_PATH = toPath(NETCONF_DISCARD_CHANGES_QNAME);
162 public static final QName NETCONF_TYPE_QNAME = QName.create(NETCONF_QNAME, "type").intern();
163 public static final QName NETCONF_FILTER_QNAME = QName.create(NETCONF_QNAME, "filter").intern();
164 public static final QName NETCONF_GET_QNAME = QName.create(NETCONF_QNAME, "get").intern();
165 public static final NodeIdentifier NETCONF_GET_NODEID = NodeIdentifier.create(NETCONF_GET_QNAME);
166 public static final SchemaPath NETCONF_GET_PATH = toPath(NETCONF_GET_QNAME);
167 public static final QName NETCONF_RPC_QNAME = QName.create(NETCONF_QNAME, "rpc").intern();
168 public static final QName YANG_QNAME = null;
169 public static final URI NETCONF_ACTION_NAMESPACE = URI.create("urn:ietf:params:xml:ns:yang:1");
170 public static final String NETCONF_ACTION = "action";
172 public static final URI NETCONF_ROLLBACK_ON_ERROR_URI = URI
173 .create("urn:ietf:params:netconf:capability:rollback-on-error:1.0");
174 public static final String ROLLBACK_ON_ERROR_OPTION = "rollback-on-error";
176 public static final URI NETCONF_CANDIDATE_URI = URI
177 .create("urn:ietf:params:netconf:capability:candidate:1.0");
179 public static final URI NETCONF_NOTIFICATONS_URI = URI
180 .create("urn:ietf:params:netconf:capability:notification:1.0");
182 public static final URI NETCONF_RUNNING_WRITABLE_URI = URI
183 .create("urn:ietf:params:netconf:capability:writable-running:1.0");
185 public static final QName NETCONF_LOCK_QNAME = QName.create(NETCONF_QNAME, "lock").intern();
186 public static final NodeIdentifier NETCONF_LOCK_NODEID = NodeIdentifier.create(NETCONF_LOCK_QNAME);
187 public static final SchemaPath NETCONF_LOCK_PATH = toPath(NETCONF_LOCK_QNAME);
188 public static final QName NETCONF_UNLOCK_QNAME = QName.create(NETCONF_QNAME, "unlock").intern();
189 public static final NodeIdentifier NETCONF_UNLOCK_NODEID = NodeIdentifier.create(NETCONF_UNLOCK_QNAME);
190 public static final SchemaPath NETCONF_UNLOCK_PATH = toPath(NETCONF_UNLOCK_QNAME);
192 public static final NodeIdentifier EDIT_CONTENT_NODEID = NodeIdentifier.create(EditContent.QNAME);
194 // Discard changes message
195 public static final ContainerNode DISCARD_CHANGES_RPC_CONTENT = Builders.containerBuilder()
196 .withNodeIdentifier(NodeIdentifier.create(NETCONF_DISCARD_CHANGES_QNAME)).build();
198 // Commit changes message
199 public static final ContainerNode COMMIT_RPC_CONTENT = Builders.containerBuilder()
200 .withNodeIdentifier(NodeIdentifier.create(NETCONF_COMMIT_QNAME)).build();
203 public static final ContainerNode GET_RPC_CONTENT = Builders.containerBuilder()
204 .withNodeIdentifier(NETCONF_GET_NODEID).build();
206 // Create-subscription changes message
207 public static final ContainerNode CREATE_SUBSCRIPTION_RPC_CONTENT = Builders.containerBuilder()
208 .withNodeIdentifier(NodeIdentifier.create(CREATE_SUBSCRIPTION_RPC_QNAME)).build();
210 public static final NodeIdentifier NETCONF_FILTER_NODEID = NodeIdentifier.create(NETCONF_FILTER_QNAME);
212 public static final DataContainerChild<?, ?> EMPTY_FILTER;
215 final Element element = XmlUtil.createElement(BLANK_DOCUMENT, NETCONF_FILTER_QNAME.getLocalName(),
216 Optional.of(NETCONF_FILTER_QNAME.getNamespace().toString()));
217 element.setAttributeNS(NETCONF_FILTER_QNAME.getNamespace().toString(),
218 NETCONF_TYPE_QNAME.getLocalName(), SUBTREE);
220 EMPTY_FILTER = Builders.anyXmlBuilder().withNodeIdentifier(NETCONF_FILTER_NODEID)
221 .withValue(new DOMSource(element)).build();
224 public static DataContainerChild<?, ?> toFilterStructure(final YangInstanceIdentifier identifier,
225 final SchemaContext ctx) {
226 final Element element = XmlUtil.createElement(BLANK_DOCUMENT, NETCONF_FILTER_QNAME.getLocalName(),
227 Optional.of(NETCONF_FILTER_QNAME.getNamespace().toString()));
228 element.setAttributeNS(NETCONF_FILTER_QNAME.getNamespace().toString(), NETCONF_TYPE_QNAME.getLocalName(),
232 NetconfUtil.writeFilter(identifier, new DOMResult(element), SchemaPath.ROOT, ctx);
233 } catch (IOException | XMLStreamException e) {
234 throw new IllegalStateException("Unable to serialize filter element for path " + identifier, e);
237 return Builders.anyXmlBuilder().withNodeIdentifier(NETCONF_FILTER_NODEID).withValue(new DOMSource(element))
241 public static void checkValidReply(final NetconfMessage input, final NetconfMessage output)
242 throws NetconfDocumentedException {
243 final String inputMsgId = input.getDocument().getDocumentElement().getAttribute(MESSAGE_ID_ATTR);
244 final String outputMsgId = output.getDocument().getDocumentElement().getAttribute(MESSAGE_ID_ATTR);
246 if (!inputMsgId.equals(outputMsgId)) {
247 final Map<String, String> errorInfo = ImmutableMap.<String, String>builder()
248 .put("actual-message-id", outputMsgId)
249 .put("expected-message-id", inputMsgId)
252 throw new NetconfDocumentedException("Response message contained unknown \"message-id\"",
253 null, NetconfDocumentedException.ErrorType.PROTOCOL,
254 NetconfDocumentedException.ErrorTag.BAD_ATTRIBUTE,
255 NetconfDocumentedException.ErrorSeverity.ERROR, errorInfo);
259 public static void checkSuccessReply(final NetconfMessage output) throws NetconfDocumentedException {
260 if (NetconfMessageUtil.isErrorMessage(output)) {
261 throw NetconfDocumentedException.fromXMLDocument(output.getDocument());
265 public static RpcError toRpcError(final NetconfDocumentedException ex) {
266 final StringBuilder infoBuilder = new StringBuilder();
267 final Map<String, String> errorInfo = ex.getErrorInfo();
268 if (errorInfo != null) {
269 for (final Entry<String, String> e : errorInfo.entrySet()) {
270 infoBuilder.append('<').append(e.getKey()).append('>').append(e.getValue())
271 .append("</").append(e.getKey()).append('>');
276 final ErrorSeverity severity = toRpcErrorSeverity(ex.getErrorSeverity());
277 return severity == ErrorSeverity.ERROR
278 ? RpcResultBuilder.newError(toRpcErrorType(ex.getErrorType()), ex.getErrorTag().getTagValue(),
279 ex.getLocalizedMessage(), null, infoBuilder.toString(), ex.getCause())
280 : RpcResultBuilder.newWarning(
281 toRpcErrorType(ex.getErrorType()), ex.getErrorTag().getTagValue(),
282 ex.getLocalizedMessage(), null, infoBuilder.toString(), ex.getCause());
285 private static ErrorSeverity toRpcErrorSeverity(final NetconfDocumentedException.ErrorSeverity severity) {
288 return RpcError.ErrorSeverity.WARNING;
290 return RpcError.ErrorSeverity.ERROR;
294 private static RpcError.ErrorType toRpcErrorType(final NetconfDocumentedException.ErrorType type) {
297 return RpcError.ErrorType.PROTOCOL;
299 return RpcError.ErrorType.RPC;
301 return RpcError.ErrorType.TRANSPORT;
303 return RpcError.ErrorType.APPLICATION;
307 public static NodeIdentifier toId(final PathArgument qname) {
308 return qname instanceof NodeIdentifier ? (NodeIdentifier) qname : toId(qname.getNodeType());
311 public static NodeIdentifier toId(final QName nodeType) {
312 return new NodeIdentifier(nodeType);
315 public static Element getDataSubtree(final Document doc) {
316 return (Element) doc.getElementsByTagNameNS(NETCONF_URI.toString(), "data").item(0);
319 public static boolean isDataRetrievalOperation(final QName rpc) {
320 return NETCONF_URI.equals(rpc.getNamespace())
321 && (NETCONF_GET_CONFIG_QNAME.getLocalName().equals(rpc.getLocalName())
322 || NETCONF_GET_QNAME.getLocalName().equals(rpc.getLocalName()));
325 public static ContainerSchemaNode createSchemaForDataRead(final SchemaContext schemaContext) {
326 return new NodeContainerProxy(NETCONF_DATA_QNAME, schemaContext.getChildNodes());
329 public static ContainerSchemaNode createSchemaForNotification(final NotificationDefinition next) {
330 return new NodeContainerProxy(next.getQName(), next.getChildNodes(), next.getAvailableAugmentations());
334 public static ContainerNode wrap(final QName name, final DataContainerChild<?, ?>... node) {
335 return wrap(toId(name), node);
338 public static ContainerNode wrap(final NodeIdentifier name, final DataContainerChild<?, ?>... node) {
339 return Builders.containerBuilder().withNodeIdentifier(name).withValue(ImmutableList.copyOf(node)).build();
342 public static AnyXmlNode createEditConfigAnyxml(
343 final SchemaContext ctx, final YangInstanceIdentifier dataPath,
344 final Optional<ModifyAction> operation,
345 final Optional<NormalizedNode<?, ?>> lastChildOverride) {
346 final NormalizedNode<?, ?> configContent;
348 if (dataPath.isEmpty()) {
349 Preconditions.checkArgument(lastChildOverride.isPresent(),
350 "Data has to be present when creating structure for top level element");
351 Preconditions.checkArgument(lastChildOverride.get() instanceof DataContainerChild<?, ?>,
352 "Data has to be either container or a list node when creating structure for top level element, "
353 + "but was: %s", lastChildOverride.get());
354 configContent = lastChildOverride.get();
356 configContent = ImmutableNodes.fromInstanceId(ctx, dataPath, lastChildOverride);
359 final NormalizedMetadata metadata = operation.map(oper -> leafMetadata(configContent, oper)).orElse(null);
360 final Element element = XmlUtil.createElement(BLANK_DOCUMENT, NETCONF_CONFIG_QNAME.getLocalName(),
361 Optional.of(NETCONF_CONFIG_QNAME.getNamespace().toString()));
364 NetconfUtil.writeNormalizedNode(configContent, metadata, new DOMResult(element), SchemaPath.ROOT, ctx);
365 } catch (IOException | XMLStreamException e) {
366 throw new IllegalStateException("Unable to serialize edit config content element for path " + dataPath, e);
369 return Builders.anyXmlBuilder().withNodeIdentifier(NETCONF_CONFIG_NODEID).withValue(new DOMSource(element))
373 private static NormalizedMetadata leafMetadata(final NormalizedNode<?, ?> node, final ModifyAction oper) {
374 final Deque<Builder> builders = new ArrayDeque<>();
376 // Step one: open builders
377 NormalizedNode<?, ?> currentNode = node;
379 builders.push(ImmutableNormalizedMetadata.builder().withIdentifier(currentNode.getIdentifier()));
380 if (currentNode instanceof NormalizedNodeContainer) {
381 final Collection<NormalizedNode<?, ?>> children =
382 ((NormalizedNodeContainer<?, ?, NormalizedNode<?, ?>>) currentNode).getValue();
383 switch (children.size()) {
388 currentNode = Iterables.getOnlyElement(children);
391 throw new IllegalStateException("Unexpected container " + currentNode);
396 } while (currentNode != null);
398 // Step two: set the top builder's metadata
399 builders.peek().withAnnotation(NETCONF_OPERATION_QNAME_LEGACY, oper.toString().toLowerCase(Locale.US));
401 // Step three: build the tree
403 final ImmutableNormalizedMetadata currentMeta = builders.pop().build();
404 final Builder parent = builders.peek();
405 if (parent != null) {
406 parent.withChild(currentMeta);
413 public static DataContainerChild<?, ?> createEditConfigStructure(final SchemaContext ctx,
414 final YangInstanceIdentifier dataPath, final Optional<ModifyAction> operation,
415 final Optional<NormalizedNode<?, ?>> lastChildOverride) {
416 return Builders.choiceBuilder().withNodeIdentifier(EDIT_CONTENT_NODEID)
417 .withChild(createEditConfigAnyxml(ctx, dataPath, operation, lastChildOverride)).build();
420 public static SchemaPath toPath(final QName rpc) {
421 return SchemaPath.ROOT.createChild(rpc);
424 public static Map.Entry<Instant, XmlElement> stripNotification(final NetconfMessage message) {
425 final XmlElement xmlElement = XmlElement.fromDomDocument(message.getDocument());
426 final List<XmlElement> childElements = xmlElement.getChildElements();
427 Preconditions.checkArgument(childElements.size() == 2, "Unable to parse notification %s, unexpected format."
428 + "\nExpected 2 childElements, actual childElements size is %s", message, childElements.size());
430 final XmlElement eventTimeElement;
431 final XmlElement notificationElement;
433 if (childElements.get(0).getName().equals(EVENT_TIME)) {
434 eventTimeElement = childElements.get(0);
435 notificationElement = childElements.get(1);
436 } else if (childElements.get(1).getName().equals(EVENT_TIME)) {
437 eventTimeElement = childElements.get(1);
438 notificationElement = childElements.get(0);
440 throw new IllegalArgumentException("Notification payload does not contain " + EVENT_TIME + " " + message);
444 return new SimpleEntry<>(
445 NetconfNotification.RFC3339_DATE_PARSER.apply(eventTimeElement.getTextContent()).toInstant(),
446 notificationElement);
447 } catch (final DocumentedException e) {
448 throw new IllegalArgumentException("Notification payload does not contain " + EVENT_TIME + " " + message,
450 } catch (final DateTimeParseException e) {
451 LOG.warn("Unable to parse event time from {}. Setting time to {}", eventTimeElement,
452 NetconfNotification.UNKNOWN_EVENT_TIME, e);
453 return new SimpleEntry<>(NetconfNotification.UNKNOWN_EVENT_TIME.toInstant(),
454 notificationElement);
458 public static DOMResult prepareDomResultForRpcRequest(final QName rpcQName, final MessageCounter counter) {
459 final Document document = XmlUtil.newDocument();
460 final Element rpcNS =
461 document.createElementNS(NETCONF_RPC_QNAME.getNamespace().toString(), NETCONF_RPC_QNAME.getLocalName());
463 rpcNS.setAttribute(MESSAGE_ID_ATTR, counter.getNewMessageId(MESSAGE_ID_PREFIX));
464 final Element elementNS = document.createElementNS(rpcQName.getNamespace().toString(), rpcQName.getLocalName());
465 rpcNS.appendChild(elementNS);
466 document.appendChild(rpcNS);
467 return new DOMResult(elementNS);
470 public static DOMResult prepareDomResultForActionRequest(final DataSchemaContextTree dataSchemaContextTree,
471 final DOMDataTreeIdentifier domDataTreeIdentifier, final SchemaPath actionSchemaPath,
472 final MessageCounter counter, final String action) {
473 final Document document = XmlUtil.newDocument();
474 final Element rpcNS =
475 document.createElementNS(NETCONF_RPC_QNAME.getNamespace().toString(), NETCONF_RPC_QNAME.getLocalName());
477 rpcNS.setAttribute(MESSAGE_ID_ATTR, counter.getNewMessageId(MESSAGE_ID_PREFIX));
479 final Element actionNS = document.createElementNS(NETCONF_ACTION_NAMESPACE.toString(), NETCONF_ACTION);
480 final DataSchemaContextNode<?> rootSchemaContextNode = dataSchemaContextTree.getRoot();
481 final Element actionData = prepareActionData(rootSchemaContextNode, actionNS,
482 domDataTreeIdentifier.getRootIdentifier().getPathArguments().iterator(), document);
484 Element specificActionElement = document.createElement(action);
485 actionData.appendChild(specificActionElement);
486 rpcNS.appendChild(actionNS);
487 document.appendChild(rpcNS);
488 return new DOMResult(specificActionElement);
491 private static Element prepareActionData(final DataSchemaContextNode<?> currentParentSchemaNode,
492 final Element actionNS, final Iterator<PathArgument> iterator, final Document document) {
493 if (iterator.hasNext()) {
494 final PathArgument next = iterator.next();
496 DataSchemaContextNode<?> current = currentParentSchemaNode.getChild(next);
497 Preconditions.checkArgument(current != null, "Invalid input: schema for argument %s not found", next);
499 if (current.isMixin()) {
500 return prepareActionData(current, actionNS, iterator, document);
503 final QName actualNS = next.getNodeType();
504 final Element actualElement = document.createElementNS(actualNS.getNamespace().toString(),
505 actualNS.getLocalName());
506 if (next instanceof NodeWithValue) {
507 actualElement.setNodeValue(((NodeWithValue) next).getValue().toString());
508 } else if (next instanceof NodeIdentifierWithPredicates) {
509 for (Entry<QName, Object> entry : ((NodeIdentifierWithPredicates) next).getKeyValues().entrySet()) {
510 final Element entryElement = document.createElementNS(entry.getKey().getNamespace().toString(),
511 entry.getKey().getLocalName());
512 entryElement.setTextContent(entry.getValue().toString());
513 entryElement.setNodeValue(entry.getValue().toString());
514 actualElement.appendChild(entryElement);
517 actionNS.appendChild(actualElement);
518 return prepareActionData(current, actualElement, iterator, document);
524 @SuppressWarnings("checkstyle:IllegalCatch")
525 public static void writeNormalizedRpc(final ContainerNode normalized, final DOMResult result,
526 final SchemaPath schemaPath,
527 final SchemaContext baseNetconfCtx) throws IOException, XMLStreamException {
528 final XMLStreamWriter writer = NetconfUtil.XML_FACTORY.createXMLStreamWriter(result);
530 try (NormalizedNodeStreamWriter normalizedNodeStreamWriter =
531 XMLStreamNormalizedNodeStreamWriter.create(writer, baseNetconfCtx, schemaPath)) {
532 try (SchemaOrderedNormalizedNodeWriter normalizedNodeWriter =
533 new SchemaOrderedNormalizedNodeWriter(normalizedNodeStreamWriter, baseNetconfCtx, schemaPath)) {
534 final Collection<DataContainerChild<?, ?>> value = normalized.getValue();
535 normalizedNodeWriter.write(value);
536 normalizedNodeWriter.flush();
542 } catch (final Exception e) {
543 LOG.warn("Unable to close resource properly", e);
548 public static RpcResult<NetconfMessage> toRpcResult(final FailedNetconfMessage message) {
549 return RpcResultBuilder.<NetconfMessage>failed()
552 new NetconfDocumentedException(
553 message.getException().getMessage(),
554 DocumentedException.ErrorType.APPLICATION,
555 DocumentedException.ErrorTag.MALFORMED_MESSAGE,
556 DocumentedException.ErrorSeverity.ERROR)))