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.NodeContainerProxy;
44 import org.opendaylight.netconf.util.messages.NetconfMessageUtil;
45 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netconf.base._1._0.rev110601.edit.config.input.EditContent;
46 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netconf.notification._1._0.rev080714.CreateSubscriptionInput;
47 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.monitoring.rev101004.NetconfState;
48 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.notifications.rev120206.NetconfCapabilityChange;
49 import org.opendaylight.yangtools.rfc7952.data.api.NormalizedMetadata;
50 import org.opendaylight.yangtools.rfc7952.data.util.ImmutableNormalizedMetadata;
51 import org.opendaylight.yangtools.rfc7952.data.util.ImmutableNormalizedMetadata.Builder;
52 import org.opendaylight.yangtools.yang.common.QName;
53 import org.opendaylight.yangtools.yang.common.RpcError;
54 import org.opendaylight.yangtools.yang.common.RpcError.ErrorSeverity;
55 import org.opendaylight.yangtools.yang.common.RpcResult;
56 import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
57 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
58 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
59 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
60 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeWithValue;
61 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
62 import org.opendaylight.yangtools.yang.data.api.schema.AnyXmlNode;
63 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
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.NormalizedNodeContainer;
67 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
68 import org.opendaylight.yangtools.yang.data.codec.xml.XMLStreamNormalizedNodeStreamWriter;
69 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
70 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
71 import org.opendaylight.yangtools.yang.data.impl.schema.SchemaOrderedNormalizedNodeWriter;
72 import org.opendaylight.yangtools.yang.data.util.DataSchemaContextNode;
73 import org.opendaylight.yangtools.yang.data.util.DataSchemaContextTree;
74 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
75 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
76 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
77 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
78 import org.slf4j.Logger;
79 import org.slf4j.LoggerFactory;
80 import org.w3c.dom.Document;
81 import org.w3c.dom.Element;
83 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 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() {}
100 public static final QName IETF_NETCONF_MONITORING =
101 QName.create(NetconfState.QNAME, "ietf-netconf-monitoring").intern();
102 public static final QName GET_DATA_QNAME = QName.create(IETF_NETCONF_MONITORING, "data").intern();
103 public static final QName GET_SCHEMA_QNAME = QName.create(IETF_NETCONF_MONITORING, "get-schema").intern();
104 public static final QName IETF_NETCONF_MONITORING_SCHEMA_FORMAT =
105 QName.create(IETF_NETCONF_MONITORING, "format").intern();
106 public static final QName IETF_NETCONF_MONITORING_SCHEMA_LOCATION =
107 QName.create(IETF_NETCONF_MONITORING, "location").intern();
108 public static final QName IETF_NETCONF_MONITORING_SCHEMA_IDENTIFIER =
109 QName.create(IETF_NETCONF_MONITORING, "identifier").intern();
110 public static final QName IETF_NETCONF_MONITORING_SCHEMA_VERSION =
111 QName.create(IETF_NETCONF_MONITORING, "version").intern();
112 public static final QName IETF_NETCONF_MONITORING_SCHEMA_NAMESPACE =
113 QName.create(IETF_NETCONF_MONITORING, "namespace").intern();
115 public static final QName IETF_NETCONF_NOTIFICATIONS =
116 QName.create(NetconfCapabilityChange.QNAME, "ietf-netconf-notifications").intern();
118 public static final QName NETCONF_QNAME =
119 QName.create("urn:ietf:params:xml:ns:netconf:base:1.0", "2011-06-01", "netconf").intern();
120 public static final URI NETCONF_URI = NETCONF_QNAME.getNamespace();
122 public static final QName NETCONF_DATA_QNAME = QName.create(NETCONF_QNAME, "data").intern();
123 public static final NodeIdentifier NETCONF_DATA_NODEID = NodeIdentifier.create(NETCONF_DATA_QNAME);
125 public static final QName NETCONF_RPC_REPLY_QNAME = QName.create(NETCONF_QNAME, "rpc-reply").intern();
126 public static final NodeIdentifier NETCONF_RPC_REPLY_NODEID = NodeIdentifier.create(NETCONF_RPC_REPLY_QNAME);
128 public static final QName NETCONF_OK_QNAME = QName.create(NETCONF_QNAME, "ok").intern();
129 public static final QName NETCONF_ERROR_OPTION_QNAME = QName.create(NETCONF_QNAME, "error-option").intern();
130 public static final NodeIdentifier NETCONF_ERROR_OPTION_NODEID = NodeIdentifier.create(NETCONF_ERROR_OPTION_QNAME);
131 public static final QName NETCONF_RUNNING_QNAME = QName.create(NETCONF_QNAME, "running").intern();
132 public static final QName NETCONF_SOURCE_QNAME = QName.create(NETCONF_QNAME, "source").intern();
133 public static final NodeIdentifier NETCONF_SOURCE_NODEID = NodeIdentifier.create(NETCONF_SOURCE_QNAME);
134 public static final QName NETCONF_CANDIDATE_QNAME = QName.create(NETCONF_QNAME, "candidate").intern();
135 public static final QName NETCONF_TARGET_QNAME = QName.create(NETCONF_QNAME, "target").intern();
136 public static final NodeIdentifier NETCONF_TARGET_NODEID = NodeIdentifier.create(NETCONF_TARGET_QNAME);
137 public static final QName NETCONF_CONFIG_QNAME = QName.create(NETCONF_QNAME, "config").intern();
138 public static final NodeIdentifier NETCONF_CONFIG_NODEID = NodeIdentifier.create(NETCONF_CONFIG_QNAME);
140 public static final QName NETCONF_COMMIT_QNAME = QName.create(NETCONF_QNAME, "commit").intern();
141 public static final SchemaPath NETCONF_COMMIT_PATH = toPath(NETCONF_COMMIT_QNAME);
142 public static final QName NETCONF_VALIDATE_QNAME = QName.create(NETCONF_QNAME, "validate").intern();
143 public static final NodeIdentifier NETCONF_VALIDATE_NODEID = NodeIdentifier.create(NETCONF_VALIDATE_QNAME);
144 public static final SchemaPath NETCONF_VALIDATE_PATH = toPath(NETCONF_VALIDATE_QNAME);
145 public static final QName NETCONF_COPY_CONFIG_QNAME = QName.create(NETCONF_QNAME, "copy-config").intern();
146 public static final NodeIdentifier NETCONF_COPY_CONFIG_NODEID = NodeIdentifier.create(NETCONF_COPY_CONFIG_QNAME);
147 public static final SchemaPath NETCONF_COPY_CONFIG_PATH = toPath(NETCONF_COPY_CONFIG_QNAME);
149 public static final QName NETCONF_OPERATION_QNAME = QName.create(NETCONF_QNAME, "operation").intern();
150 private static final QName NETCONF_OPERATION_QNAME_LEGACY = NETCONF_OPERATION_QNAME.withoutRevision().intern();
151 public static final QName NETCONF_DEFAULT_OPERATION_QNAME =
152 QName.create(NETCONF_OPERATION_QNAME, "default-operation").intern();
153 public static final NodeIdentifier NETCONF_DEFAULT_OPERATION_NODEID =
154 NodeIdentifier.create(NETCONF_DEFAULT_OPERATION_QNAME);
155 public static final QName NETCONF_EDIT_CONFIG_QNAME = QName.create(NETCONF_QNAME, "edit-config").intern();
156 public static final NodeIdentifier NETCONF_EDIT_CONFIG_NODEID = NodeIdentifier.create(NETCONF_EDIT_CONFIG_QNAME);
157 public static final SchemaPath NETCONF_EDIT_CONFIG_PATH = toPath(NETCONF_EDIT_CONFIG_QNAME);
158 public static final QName NETCONF_GET_CONFIG_QNAME = QName.create(NETCONF_QNAME, "get-config");
159 public static final NodeIdentifier NETCONF_GET_CONFIG_NODEID = NodeIdentifier.create(NETCONF_GET_CONFIG_QNAME);
160 public static final SchemaPath NETCONF_GET_CONFIG_PATH = toPath(NETCONF_GET_CONFIG_QNAME);
161 public static final QName NETCONF_DISCARD_CHANGES_QNAME = QName.create(NETCONF_QNAME, "discard-changes");
162 public static final SchemaPath NETCONF_DISCARD_CHANGES_PATH = toPath(NETCONF_DISCARD_CHANGES_QNAME);
163 public static final QName NETCONF_TYPE_QNAME = QName.create(NETCONF_QNAME, "type").intern();
164 public static final QName NETCONF_FILTER_QNAME = QName.create(NETCONF_QNAME, "filter").intern();
165 public static final QName NETCONF_GET_QNAME = QName.create(NETCONF_QNAME, "get").intern();
166 public static final NodeIdentifier NETCONF_GET_NODEID = NodeIdentifier.create(NETCONF_GET_QNAME);
167 public static final SchemaPath NETCONF_GET_PATH = toPath(NETCONF_GET_QNAME);
168 public static final QName NETCONF_RPC_QNAME = QName.create(NETCONF_QNAME, "rpc").intern();
169 public static final QName YANG_QNAME = null;
170 public static final URI NETCONF_ACTION_NAMESPACE = URI.create("urn:ietf:params:xml:ns:yang:1");
171 public static final String NETCONF_ACTION = "action";
173 public static final URI NETCONF_ROLLBACK_ON_ERROR_URI = URI
174 .create("urn:ietf:params:netconf:capability:rollback-on-error:1.0");
175 public static final String ROLLBACK_ON_ERROR_OPTION = "rollback-on-error";
177 public static final URI NETCONF_CANDIDATE_URI = URI
178 .create("urn:ietf:params:netconf:capability:candidate:1.0");
180 public static final URI NETCONF_NOTIFICATONS_URI = URI
181 .create("urn:ietf:params:netconf:capability:notification:1.0");
183 public static final URI NETCONF_RUNNING_WRITABLE_URI = URI
184 .create("urn:ietf:params:netconf:capability:writable-running:1.0");
186 public static final QName NETCONF_LOCK_QNAME = QName.create(NETCONF_QNAME, "lock").intern();
187 public static final NodeIdentifier NETCONF_LOCK_NODEID = NodeIdentifier.create(NETCONF_LOCK_QNAME);
188 public static final SchemaPath NETCONF_LOCK_PATH = toPath(NETCONF_LOCK_QNAME);
189 public static final QName NETCONF_UNLOCK_QNAME = QName.create(NETCONF_QNAME, "unlock").intern();
190 public static final NodeIdentifier NETCONF_UNLOCK_NODEID = NodeIdentifier.create(NETCONF_UNLOCK_QNAME);
191 public static final SchemaPath NETCONF_UNLOCK_PATH = toPath(NETCONF_UNLOCK_QNAME);
193 public static final NodeIdentifier EDIT_CONTENT_NODEID = NodeIdentifier.create(EditContent.QNAME);
195 // Discard changes message
196 public static final ContainerNode DISCARD_CHANGES_RPC_CONTENT = Builders.containerBuilder()
197 .withNodeIdentifier(NodeIdentifier.create(NETCONF_DISCARD_CHANGES_QNAME)).build();
199 // Commit changes message
200 public static final ContainerNode COMMIT_RPC_CONTENT = Builders.containerBuilder()
201 .withNodeIdentifier(NodeIdentifier.create(NETCONF_COMMIT_QNAME)).build();
204 public static final ContainerNode GET_RPC_CONTENT = Builders.containerBuilder()
205 .withNodeIdentifier(NETCONF_GET_NODEID).build();
207 // Create-subscription changes message
208 public static final ContainerNode CREATE_SUBSCRIPTION_RPC_CONTENT = Builders.containerBuilder()
209 .withNodeIdentifier(NodeIdentifier.create(CREATE_SUBSCRIPTION_RPC_QNAME)).build();
211 public static final NodeIdentifier NETCONF_FILTER_NODEID = NodeIdentifier.create(NETCONF_FILTER_QNAME);
213 public static final DataContainerChild<?, ?> EMPTY_FILTER;
216 final Element element = XmlUtil.createElement(BLANK_DOCUMENT, NETCONF_FILTER_QNAME.getLocalName(),
217 Optional.of(NETCONF_FILTER_QNAME.getNamespace().toString()));
218 element.setAttributeNS(NETCONF_FILTER_QNAME.getNamespace().toString(),
219 NETCONF_TYPE_QNAME.getLocalName(), SUBTREE);
221 EMPTY_FILTER = Builders.anyXmlBuilder().withNodeIdentifier(NETCONF_FILTER_NODEID)
222 .withValue(new DOMSource(element)).build();
225 public static DataContainerChild<?, ?> toFilterStructure(final YangInstanceIdentifier identifier,
226 final SchemaContext ctx) {
227 final Element element = XmlUtil.createElement(BLANK_DOCUMENT, NETCONF_FILTER_QNAME.getLocalName(),
228 Optional.of(NETCONF_FILTER_QNAME.getNamespace().toString()));
229 element.setAttributeNS(NETCONF_FILTER_QNAME.getNamespace().toString(), NETCONF_TYPE_QNAME.getLocalName(),
233 NetconfUtil.writeFilter(identifier, new DOMResult(element), SchemaPath.ROOT, ctx);
234 } catch (IOException | XMLStreamException e) {
235 throw new IllegalStateException("Unable to serialize filter element for path " + identifier, e);
238 return Builders.anyXmlBuilder().withNodeIdentifier(NETCONF_FILTER_NODEID).withValue(new DOMSource(element))
242 public static void checkValidReply(final NetconfMessage input, final NetconfMessage output)
243 throws NetconfDocumentedException {
244 final String inputMsgId = input.getDocument().getDocumentElement().getAttribute(MESSAGE_ID_ATTR);
245 final String outputMsgId = output.getDocument().getDocumentElement().getAttribute(MESSAGE_ID_ATTR);
247 if (!inputMsgId.equals(outputMsgId)) {
248 final Map<String, String> errorInfo = ImmutableMap.<String, String>builder()
249 .put("actual-message-id", outputMsgId)
250 .put("expected-message-id", inputMsgId)
253 throw new NetconfDocumentedException("Response message contained unknown \"message-id\"",
254 null, NetconfDocumentedException.ErrorType.PROTOCOL,
255 NetconfDocumentedException.ErrorTag.BAD_ATTRIBUTE,
256 NetconfDocumentedException.ErrorSeverity.ERROR, errorInfo);
260 public static void checkSuccessReply(final NetconfMessage output) throws NetconfDocumentedException {
261 if (NetconfMessageUtil.isErrorMessage(output)) {
262 throw NetconfDocumentedException.fromXMLDocument(output.getDocument());
266 public static RpcError toRpcError(final NetconfDocumentedException ex) {
267 final StringBuilder infoBuilder = new StringBuilder();
268 final Map<String, String> errorInfo = ex.getErrorInfo();
269 if (errorInfo != null) {
270 for (final Entry<String, String> e : errorInfo.entrySet()) {
271 infoBuilder.append('<').append(e.getKey()).append('>').append(e.getValue())
272 .append("</").append(e.getKey()).append('>');
277 final ErrorSeverity severity = toRpcErrorSeverity(ex.getErrorSeverity());
278 return severity == ErrorSeverity.ERROR
279 ? RpcResultBuilder.newError(toRpcErrorType(ex.getErrorType()), ex.getErrorTag().getTagValue(),
280 ex.getLocalizedMessage(), null, infoBuilder.toString(), ex.getCause())
281 : RpcResultBuilder.newWarning(
282 toRpcErrorType(ex.getErrorType()), ex.getErrorTag().getTagValue(),
283 ex.getLocalizedMessage(), null, infoBuilder.toString(), ex.getCause());
286 private static ErrorSeverity toRpcErrorSeverity(final NetconfDocumentedException.ErrorSeverity severity) {
289 return RpcError.ErrorSeverity.WARNING;
291 return RpcError.ErrorSeverity.ERROR;
295 private static RpcError.ErrorType toRpcErrorType(final NetconfDocumentedException.ErrorType type) {
298 return RpcError.ErrorType.PROTOCOL;
300 return RpcError.ErrorType.RPC;
302 return RpcError.ErrorType.TRANSPORT;
304 return RpcError.ErrorType.APPLICATION;
308 public static NodeIdentifier toId(final PathArgument qname) {
309 return qname instanceof NodeIdentifier ? (NodeIdentifier) qname : toId(qname.getNodeType());
312 public static NodeIdentifier toId(final QName nodeType) {
313 return new NodeIdentifier(nodeType);
316 public static Element getDataSubtree(final Document doc) {
317 return (Element) doc.getElementsByTagNameNS(NETCONF_URI.toString(), "data").item(0);
320 public static boolean isDataRetrievalOperation(final QName rpc) {
321 return NETCONF_URI.equals(rpc.getNamespace())
322 && (NETCONF_GET_CONFIG_QNAME.getLocalName().equals(rpc.getLocalName())
323 || NETCONF_GET_QNAME.getLocalName().equals(rpc.getLocalName()));
326 public static ContainerSchemaNode createSchemaForDataRead(final SchemaContext schemaContext) {
327 return new NodeContainerProxy(NETCONF_DATA_QNAME, schemaContext.getChildNodes());
330 public static ContainerSchemaNode createSchemaForNotification(final NotificationDefinition next) {
331 return new NodeContainerProxy(next.getQName(), next.getChildNodes(), next.getAvailableAugmentations());
335 public static ContainerNode wrap(final QName name, final DataContainerChild<?, ?>... node) {
336 return wrap(toId(name), node);
339 public static ContainerNode wrap(final NodeIdentifier name, final DataContainerChild<?, ?>... node) {
340 return Builders.containerBuilder().withNodeIdentifier(name).withValue(ImmutableList.copyOf(node)).build();
343 public static AnyXmlNode createEditConfigAnyxml(
344 final SchemaContext ctx, final YangInstanceIdentifier dataPath,
345 final Optional<ModifyAction> operation,
346 final Optional<NormalizedNode<?, ?>> lastChildOverride) {
347 final NormalizedNode<?, ?> configContent;
349 if (dataPath.isEmpty()) {
350 Preconditions.checkArgument(lastChildOverride.isPresent(),
351 "Data has to be present when creating structure for top level element");
352 Preconditions.checkArgument(lastChildOverride.get() instanceof DataContainerChild<?, ?>,
353 "Data has to be either container or a list node when creating structure for top level element, "
354 + "but was: %s", lastChildOverride.get());
355 configContent = lastChildOverride.get();
357 configContent = ImmutableNodes.fromInstanceId(ctx, dataPath, lastChildOverride);
360 final NormalizedMetadata metadata = operation.map(oper -> leafMetadata(configContent, oper)).orElse(null);
361 final Element element = XmlUtil.createElement(BLANK_DOCUMENT, NETCONF_CONFIG_QNAME.getLocalName(),
362 Optional.of(NETCONF_CONFIG_QNAME.getNamespace().toString()));
365 NetconfUtil.writeNormalizedNode(configContent, metadata, new DOMResult(element), SchemaPath.ROOT, ctx);
366 } catch (IOException | XMLStreamException e) {
367 throw new IllegalStateException("Unable to serialize edit config content element for path " + dataPath, e);
370 return Builders.anyXmlBuilder().withNodeIdentifier(NETCONF_CONFIG_NODEID).withValue(new DOMSource(element))
374 private static NormalizedMetadata leafMetadata(final NormalizedNode<?, ?> node, final ModifyAction oper) {
375 final Deque<Builder> builders = new ArrayDeque<>();
377 // Step one: open builders
378 NormalizedNode<?, ?> currentNode = node;
380 builders.push(ImmutableNormalizedMetadata.builder().withIdentifier(currentNode.getIdentifier()));
381 if (currentNode instanceof NormalizedNodeContainer) {
382 final Collection<NormalizedNode<?, ?>> children =
383 ((NormalizedNodeContainer<?, ?, NormalizedNode<?, ?>>) currentNode).getValue();
384 switch (children.size()) {
389 currentNode = Iterables.getOnlyElement(children);
392 throw new IllegalStateException("Unexpected container " + currentNode);
397 } while (currentNode != null);
399 // Step two: set the top builder's metadata
400 builders.peek().withAnnotation(NETCONF_OPERATION_QNAME_LEGACY, oper.toString().toLowerCase(Locale.US));
402 // Step three: build the tree
404 final ImmutableNormalizedMetadata currentMeta = builders.pop().build();
405 final Builder parent = builders.peek();
406 if (parent != null) {
407 parent.withChild(currentMeta);
414 public static DataContainerChild<?, ?> createEditConfigStructure(final SchemaContext ctx,
415 final YangInstanceIdentifier dataPath, final Optional<ModifyAction> operation,
416 final Optional<NormalizedNode<?, ?>> lastChildOverride) {
417 return Builders.choiceBuilder().withNodeIdentifier(EDIT_CONTENT_NODEID)
418 .withChild(createEditConfigAnyxml(ctx, dataPath, operation, lastChildOverride)).build();
421 public static SchemaPath toPath(final QName rpc) {
422 return SchemaPath.ROOT.createChild(rpc);
425 public static Map.Entry<Instant, XmlElement> stripNotification(final NetconfMessage message) {
426 final XmlElement xmlElement = XmlElement.fromDomDocument(message.getDocument());
427 final List<XmlElement> childElements = xmlElement.getChildElements();
428 Preconditions.checkArgument(childElements.size() == 2, "Unable to parse notification %s, unexpected format."
429 + "\nExpected 2 childElements, actual childElements size is %s", message, childElements.size());
431 final XmlElement eventTimeElement;
432 final XmlElement notificationElement;
434 if (childElements.get(0).getName().equals(EVENT_TIME)) {
435 eventTimeElement = childElements.get(0);
436 notificationElement = childElements.get(1);
437 } else if (childElements.get(1).getName().equals(EVENT_TIME)) {
438 eventTimeElement = childElements.get(1);
439 notificationElement = childElements.get(0);
441 throw new IllegalArgumentException("Notification payload does not contain " + EVENT_TIME + " " + message);
445 return new SimpleEntry<>(
446 NetconfNotification.RFC3339_DATE_PARSER.apply(eventTimeElement.getTextContent()).toInstant(),
447 notificationElement);
448 } catch (final DocumentedException e) {
449 throw new IllegalArgumentException("Notification payload does not contain " + EVENT_TIME + " " + message,
451 } catch (final DateTimeParseException e) {
452 LOG.warn("Unable to parse event time from {}. Setting time to {}", eventTimeElement,
453 NetconfNotification.UNKNOWN_EVENT_TIME, e);
454 return new SimpleEntry<>(NetconfNotification.UNKNOWN_EVENT_TIME.toInstant(),
455 notificationElement);
459 public static DOMResult prepareDomResultForRpcRequest(final QName rpcQName, final MessageCounter counter) {
460 final Document document = XmlUtil.newDocument();
461 final Element rpcNS =
462 document.createElementNS(NETCONF_RPC_QNAME.getNamespace().toString(), NETCONF_RPC_QNAME.getLocalName());
464 rpcNS.setAttribute(MESSAGE_ID_ATTR, counter.getNewMessageId(MESSAGE_ID_PREFIX));
465 final Element elementNS = document.createElementNS(rpcQName.getNamespace().toString(), rpcQName.getLocalName());
466 rpcNS.appendChild(elementNS);
467 document.appendChild(rpcNS);
468 return new DOMResult(elementNS);
471 public static DOMResult prepareDomResultForActionRequest(final DataSchemaContextTree dataSchemaContextTree,
472 final DOMDataTreeIdentifier domDataTreeIdentifier, final SchemaPath actionSchemaPath,
473 final MessageCounter counter, final String action) {
474 final Document document = XmlUtil.newDocument();
475 final Element rpcNS =
476 document.createElementNS(NETCONF_RPC_QNAME.getNamespace().toString(), NETCONF_RPC_QNAME.getLocalName());
478 rpcNS.setAttribute(MESSAGE_ID_ATTR, counter.getNewMessageId(MESSAGE_ID_PREFIX));
480 final Element actionNS = document.createElementNS(NETCONF_ACTION_NAMESPACE.toString(), NETCONF_ACTION);
481 final DataSchemaContextNode<?> rootSchemaContextNode = dataSchemaContextTree.getRoot();
482 final Element actionData = prepareActionData(rootSchemaContextNode, actionNS,
483 domDataTreeIdentifier.getRootIdentifier().getPathArguments().iterator(), document);
485 final Element specificActionElement = document.createElement(action);
486 actionData.appendChild(specificActionElement);
487 rpcNS.appendChild(actionNS);
488 document.appendChild(rpcNS);
489 return new DOMResult(specificActionElement);
492 private static Element prepareActionData(final DataSchemaContextNode<?> currentParentSchemaNode,
493 final Element actionNS, final Iterator<PathArgument> iterator, final Document document) {
494 if (iterator.hasNext()) {
495 final PathArgument next = iterator.next();
497 final DataSchemaContextNode<?> current = currentParentSchemaNode.getChild(next);
498 Preconditions.checkArgument(current != null, "Invalid input: schema for argument %s not found", next);
500 if (current.isMixin()) {
501 return prepareActionData(current, actionNS, iterator, document);
504 final QName actualNS = next.getNodeType();
505 final Element actualElement = document.createElementNS(actualNS.getNamespace().toString(),
506 actualNS.getLocalName());
507 if (next instanceof NodeWithValue) {
508 actualElement.setNodeValue(((NodeWithValue) next).getValue().toString());
509 } else if (next instanceof NodeIdentifierWithPredicates) {
510 for (Entry<QName, Object> entry : ((NodeIdentifierWithPredicates) next).getKeyValues().entrySet()) {
511 final Element entryElement = document.createElementNS(entry.getKey().getNamespace().toString(),
512 entry.getKey().getLocalName());
513 entryElement.setTextContent(entry.getValue().toString());
514 entryElement.setNodeValue(entry.getValue().toString());
515 actualElement.appendChild(entryElement);
518 actionNS.appendChild(actualElement);
519 return prepareActionData(current, actualElement, iterator, document);
525 @SuppressWarnings("checkstyle:IllegalCatch")
526 public static void writeNormalizedRpc(final ContainerNode normalized, final DOMResult result,
527 final SchemaPath schemaPath,
528 final SchemaContext baseNetconfCtx) throws IOException, XMLStreamException {
529 final XMLStreamWriter writer = NetconfUtil.XML_FACTORY.createXMLStreamWriter(result);
531 try (NormalizedNodeStreamWriter normalizedNodeStreamWriter =
532 XMLStreamNormalizedNodeStreamWriter.create(writer, baseNetconfCtx, schemaPath)) {
533 try (SchemaOrderedNormalizedNodeWriter normalizedNodeWriter =
534 new SchemaOrderedNormalizedNodeWriter(normalizedNodeStreamWriter, baseNetconfCtx, schemaPath)) {
535 final Collection<DataContainerChild<?, ?>> value = normalized.getValue();
536 normalizedNodeWriter.write(value);
537 normalizedNodeWriter.flush();
543 } catch (final Exception e) {
544 LOG.warn("Unable to close resource properly", e);
549 public static RpcResult<NetconfMessage> toRpcResult(final FailedNetconfMessage message) {
550 return RpcResultBuilder.<NetconfMessage>failed()
553 new NetconfDocumentedException(
554 message.getException().getMessage(),
555 DocumentedException.ErrorType.APPLICATION,
556 DocumentedException.ErrorTag.MALFORMED_MESSAGE,
557 DocumentedException.ErrorSeverity.ERROR)))