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 java.io.IOException;
15 import java.time.Instant;
16 import java.time.format.DateTimeParseException;
17 import java.util.AbstractMap;
18 import java.util.AbstractMap.SimpleEntry;
19 import java.util.Collection;
20 import java.util.Iterator;
21 import java.util.List;
23 import java.util.Map.Entry;
24 import java.util.Optional;
25 import javax.xml.stream.XMLStreamException;
26 import javax.xml.stream.XMLStreamWriter;
27 import javax.xml.transform.dom.DOMResult;
28 import javax.xml.transform.dom.DOMSource;
29 import org.opendaylight.mdsal.dom.api.DOMDataTreeIdentifier;
30 import org.opendaylight.netconf.api.DocumentedException;
31 import org.opendaylight.netconf.api.FailedNetconfMessage;
32 import org.opendaylight.netconf.api.NetconfDocumentedException;
33 import org.opendaylight.netconf.api.NetconfMessage;
34 import org.opendaylight.netconf.api.xml.XmlElement;
35 import org.opendaylight.netconf.api.xml.XmlUtil;
36 import org.opendaylight.netconf.notifications.NetconfNotification;
37 import org.opendaylight.netconf.sal.connect.util.MessageCounter;
38 import org.opendaylight.netconf.util.NetconfUtil;
39 import org.opendaylight.netconf.util.messages.NetconfMessageUtil;
40 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netconf.base._1._0.rev110601.edit.config.input.EditContent;
41 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netconf.notification._1._0.rev080714.CreateSubscriptionInput;
42 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.monitoring.rev101004.NetconfState;
43 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.notifications.rev120206.NetconfCapabilityChange;
44 import org.opendaylight.yangtools.yang.common.QName;
45 import org.opendaylight.yangtools.yang.common.RpcError;
46 import org.opendaylight.yangtools.yang.common.RpcError.ErrorSeverity;
47 import org.opendaylight.yangtools.yang.common.RpcResult;
48 import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
49 import org.opendaylight.yangtools.yang.data.api.ModifyAction;
50 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
51 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
52 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
53 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeWithValue;
54 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
55 import org.opendaylight.yangtools.yang.data.api.schema.AnyXmlNode;
56 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
57 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
58 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
59 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
60 import org.opendaylight.yangtools.yang.data.codec.xml.XMLStreamNormalizedNodeStreamWriter;
61 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
62 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
63 import org.opendaylight.yangtools.yang.data.impl.schema.SchemaOrderedNormalizedNodeWriter;
64 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.NormalizedNodeAttrBuilder;
65 import org.opendaylight.yangtools.yang.data.util.DataSchemaContextNode;
66 import org.opendaylight.yangtools.yang.data.util.DataSchemaContextTree;
67 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
68 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
69 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
70 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
71 import org.slf4j.Logger;
72 import org.slf4j.LoggerFactory;
73 import org.w3c.dom.Document;
74 import org.w3c.dom.Element;
76 public final class NetconfMessageTransformUtil {
78 private static final Logger LOG = LoggerFactory.getLogger(NetconfMessageTransformUtil.class);
80 public static final String MESSAGE_ID_PREFIX = "m";
81 public static final String MESSAGE_ID_ATTR = "message-id";
83 public static final QName CREATE_SUBSCRIPTION_RPC_QNAME =
84 QName.create(CreateSubscriptionInput.QNAME, "create-subscription").intern();
85 private static final String SUBTREE = "subtree";
87 // Blank document used for creation of new DOM nodes
88 private static final Document BLANK_DOCUMENT = XmlUtil.newDocument();
89 public static final String EVENT_TIME = "eventTime";
91 private NetconfMessageTransformUtil() {}
93 public static final QName IETF_NETCONF_MONITORING =
94 QName.create(NetconfState.QNAME, "ietf-netconf-monitoring").intern();
95 public static final QName GET_DATA_QNAME = QName.create(IETF_NETCONF_MONITORING, "data").intern();
96 public static final QName GET_SCHEMA_QNAME = QName.create(IETF_NETCONF_MONITORING, "get-schema").intern();
97 public static final QName IETF_NETCONF_MONITORING_SCHEMA_FORMAT =
98 QName.create(IETF_NETCONF_MONITORING, "format").intern();
99 public static final QName IETF_NETCONF_MONITORING_SCHEMA_LOCATION =
100 QName.create(IETF_NETCONF_MONITORING, "location").intern();
101 public static final QName IETF_NETCONF_MONITORING_SCHEMA_IDENTIFIER =
102 QName.create(IETF_NETCONF_MONITORING, "identifier").intern();
103 public static final QName IETF_NETCONF_MONITORING_SCHEMA_VERSION =
104 QName.create(IETF_NETCONF_MONITORING, "version").intern();
105 public static final QName IETF_NETCONF_MONITORING_SCHEMA_NAMESPACE =
106 QName.create(IETF_NETCONF_MONITORING, "namespace").intern();
108 public static final QName IETF_NETCONF_NOTIFICATIONS =
109 QName.create(NetconfCapabilityChange.QNAME, "ietf-netconf-notifications").intern();
111 public static final QName NETCONF_QNAME =
112 QName.create("urn:ietf:params:xml:ns:netconf:base:1.0", "2011-06-01", "netconf").intern();
113 public static final URI NETCONF_URI = NETCONF_QNAME.getNamespace();
115 public static final QName NETCONF_DATA_QNAME = QName.create(NETCONF_QNAME, "data").intern();
116 public static final NodeIdentifier NETCONF_DATA_NODEID = NodeIdentifier.create(NETCONF_DATA_QNAME);
118 public static final QName NETCONF_RPC_REPLY_QNAME = QName.create(NETCONF_QNAME, "rpc-reply").intern();
119 public static final QName NETCONF_OK_QNAME = QName.create(NETCONF_QNAME, "ok").intern();
120 public static final QName NETCONF_ERROR_OPTION_QNAME = QName.create(NETCONF_QNAME, "error-option").intern();
121 public static final NodeIdentifier NETCONF_ERROR_OPTION_NODEID = NodeIdentifier.create(NETCONF_ERROR_OPTION_QNAME);
122 public static final QName NETCONF_RUNNING_QNAME = QName.create(NETCONF_QNAME, "running").intern();
123 public static final QName NETCONF_SOURCE_QNAME = QName.create(NETCONF_QNAME, "source").intern();
124 public static final NodeIdentifier NETCONF_SOURCE_NODEID = NodeIdentifier.create(NETCONF_SOURCE_QNAME);
125 public static final QName NETCONF_CANDIDATE_QNAME = QName.create(NETCONF_QNAME, "candidate").intern();
126 public static final QName NETCONF_TARGET_QNAME = QName.create(NETCONF_QNAME, "target").intern();
127 public static final NodeIdentifier NETCONF_TARGET_NODEID = NodeIdentifier.create(NETCONF_TARGET_QNAME);
128 public static final QName NETCONF_CONFIG_QNAME = QName.create(NETCONF_QNAME, "config").intern();
129 public static final NodeIdentifier NETCONF_CONFIG_NODEID = NodeIdentifier.create(NETCONF_CONFIG_QNAME);
131 public static final QName NETCONF_COMMIT_QNAME = QName.create(NETCONF_QNAME, "commit").intern();
132 public static final SchemaPath NETCONF_COMMIT_PATH = toPath(NETCONF_COMMIT_QNAME);
133 public static final QName NETCONF_VALIDATE_QNAME = QName.create(NETCONF_QNAME, "validate").intern();
134 public static final NodeIdentifier NETCONF_VALIDATE_NODEID = NodeIdentifier.create(NETCONF_VALIDATE_QNAME);
135 public static final SchemaPath NETCONF_VALIDATE_PATH = toPath(NETCONF_VALIDATE_QNAME);
136 public static final QName NETCONF_COPY_CONFIG_QNAME = QName.create(NETCONF_QNAME, "copy-config").intern();
137 public static final NodeIdentifier NETCONF_COPY_CONFIG_NODEID = NodeIdentifier.create(NETCONF_COPY_CONFIG_QNAME);
138 public static final SchemaPath NETCONF_COPY_CONFIG_PATH = toPath(NETCONF_COPY_CONFIG_QNAME);
140 public static final QName NETCONF_OPERATION_QNAME = QName.create(NETCONF_QNAME, "operation").intern();
141 public static final QName NETCONF_DEFAULT_OPERATION_QNAME =
142 QName.create(NETCONF_OPERATION_QNAME, "default-operation").intern();
143 public static final NodeIdentifier NETCONF_DEFAULT_OPERATION_NODEID =
144 NodeIdentifier.create(NETCONF_DEFAULT_OPERATION_QNAME);
145 public static final QName NETCONF_EDIT_CONFIG_QNAME = QName.create(NETCONF_QNAME, "edit-config").intern();
146 public static final NodeIdentifier NETCONF_EDIT_CONFIG_NODEID = NodeIdentifier.create(NETCONF_EDIT_CONFIG_QNAME);
147 public static final SchemaPath NETCONF_EDIT_CONFIG_PATH = toPath(NETCONF_EDIT_CONFIG_QNAME);
148 public static final QName NETCONF_GET_CONFIG_QNAME = QName.create(NETCONF_QNAME, "get-config");
149 public static final NodeIdentifier NETCONF_GET_CONFIG_NODEID = NodeIdentifier.create(NETCONF_GET_CONFIG_QNAME);
150 public static final SchemaPath NETCONF_GET_CONFIG_PATH = toPath(NETCONF_GET_CONFIG_QNAME);
151 public static final QName NETCONF_DISCARD_CHANGES_QNAME = QName.create(NETCONF_QNAME, "discard-changes");
152 public static final SchemaPath NETCONF_DISCARD_CHANGES_PATH = toPath(NETCONF_DISCARD_CHANGES_QNAME);
153 public static final QName NETCONF_TYPE_QNAME = QName.create(NETCONF_QNAME, "type").intern();
154 public static final QName NETCONF_FILTER_QNAME = QName.create(NETCONF_QNAME, "filter").intern();
155 public static final QName NETCONF_GET_QNAME = QName.create(NETCONF_QNAME, "get").intern();
156 public static final NodeIdentifier NETCONF_GET_NODEID = NodeIdentifier.create(NETCONF_GET_QNAME);
157 public static final SchemaPath NETCONF_GET_PATH = toPath(NETCONF_GET_QNAME);
158 public static final QName NETCONF_RPC_QNAME = QName.create(NETCONF_QNAME, "rpc").intern();
159 public static final QName YANG_QNAME = null;
160 public static final URI NETCONF_ACTION_NAMESPACE = URI.create("urn:ietf:params:xml:ns:yang:1");
161 public static final String NETCONF_ACTION = "action";
163 public static final URI NETCONF_ROLLBACK_ON_ERROR_URI = URI
164 .create("urn:ietf:params:netconf:capability:rollback-on-error:1.0");
165 public static final String ROLLBACK_ON_ERROR_OPTION = "rollback-on-error";
167 public static final URI NETCONF_CANDIDATE_URI = URI
168 .create("urn:ietf:params:netconf:capability:candidate:1.0");
170 public static final URI NETCONF_NOTIFICATONS_URI = URI
171 .create("urn:ietf:params:netconf:capability:notification:1.0");
173 public static final URI NETCONF_RUNNING_WRITABLE_URI = URI
174 .create("urn:ietf:params:netconf:capability:writable-running:1.0");
176 public static final QName NETCONF_LOCK_QNAME = QName.create(NETCONF_QNAME, "lock").intern();
177 public static final NodeIdentifier NETCONF_LOCK_NODEID = NodeIdentifier.create(NETCONF_LOCK_QNAME);
178 public static final SchemaPath NETCONF_LOCK_PATH = toPath(NETCONF_LOCK_QNAME);
179 public static final QName NETCONF_UNLOCK_QNAME = QName.create(NETCONF_QNAME, "unlock").intern();
180 public static final NodeIdentifier NETCONF_UNLOCK_NODEID = NodeIdentifier.create(NETCONF_UNLOCK_QNAME);
181 public static final SchemaPath NETCONF_UNLOCK_PATH = toPath(NETCONF_UNLOCK_QNAME);
183 public static final NodeIdentifier EDIT_CONTENT_NODEID = NodeIdentifier.create(EditContent.QNAME);
185 // Discard changes message
186 public static final ContainerNode DISCARD_CHANGES_RPC_CONTENT = Builders.containerBuilder()
187 .withNodeIdentifier(NodeIdentifier.create(NETCONF_DISCARD_CHANGES_QNAME)).build();
189 // Commit changes message
190 public static final ContainerNode COMMIT_RPC_CONTENT = Builders.containerBuilder()
191 .withNodeIdentifier(NodeIdentifier.create(NETCONF_COMMIT_QNAME)).build();
194 public static final ContainerNode GET_RPC_CONTENT = Builders.containerBuilder()
195 .withNodeIdentifier(NETCONF_GET_NODEID).build();
197 // Create-subscription changes message
198 public static final ContainerNode CREATE_SUBSCRIPTION_RPC_CONTENT = Builders.containerBuilder()
199 .withNodeIdentifier(NodeIdentifier.create(CREATE_SUBSCRIPTION_RPC_QNAME)).build();
201 private static final NodeIdentifier NETCONF_FILTER_NODEID = NodeIdentifier.create(NETCONF_FILTER_QNAME);
202 private static final Map<QName, String> SUBTREE_FILTER_ATTRIBUTES = ImmutableMap.of(NETCONF_TYPE_QNAME, SUBTREE);
204 public static final DataContainerChild<?, ?> EMPTY_FILTER;
207 final NormalizedNodeAttrBuilder<NodeIdentifier, DOMSource, AnyXmlNode> anyXmlBuilder =
208 Builders.anyXmlBuilder().withNodeIdentifier(NETCONF_FILTER_NODEID)
209 .withAttributes(SUBTREE_FILTER_ATTRIBUTES);
211 final Element element = XmlUtil.createElement(BLANK_DOCUMENT, NETCONF_FILTER_QNAME.getLocalName(),
212 Optional.of(NETCONF_FILTER_QNAME.getNamespace().toString()));
213 element.setAttributeNS(NETCONF_FILTER_QNAME.getNamespace().toString(),
214 NETCONF_TYPE_QNAME.getLocalName(), "subtree");
216 anyXmlBuilder.withValue(new DOMSource(element));
218 EMPTY_FILTER = anyXmlBuilder.build();
221 public static DataContainerChild<?, ?> toFilterStructure(final YangInstanceIdentifier identifier,
222 final SchemaContext ctx) {
223 final NormalizedNodeAttrBuilder<NodeIdentifier, DOMSource, AnyXmlNode> anyXmlBuilder = Builders.anyXmlBuilder()
224 .withNodeIdentifier(NETCONF_FILTER_NODEID).withAttributes(SUBTREE_FILTER_ATTRIBUTES);
225 final Element element = XmlUtil.createElement(BLANK_DOCUMENT, NETCONF_FILTER_QNAME.getLocalName(),
226 Optional.of(NETCONF_FILTER_QNAME.getNamespace().toString()));
227 element.setAttributeNS(NETCONF_FILTER_QNAME.getNamespace().toString(), NETCONF_TYPE_QNAME.getLocalName(),
231 NetconfUtil.writeFilter(identifier, new DOMResult(element), SchemaPath.ROOT, ctx);
232 } catch (IOException | XMLStreamException e) {
233 throw new IllegalStateException("Unable to serialize filter element for path " + identifier, e);
235 anyXmlBuilder.withValue(new DOMSource(element));
237 return anyXmlBuilder.build();
240 public static void checkValidReply(final NetconfMessage input, final NetconfMessage output)
241 throws NetconfDocumentedException {
242 final String inputMsgId = input.getDocument().getDocumentElement().getAttribute(MESSAGE_ID_ATTR);
243 final String outputMsgId = output.getDocument().getDocumentElement().getAttribute(MESSAGE_ID_ATTR);
245 if (!inputMsgId.equals(outputMsgId)) {
246 final Map<String, String> errorInfo = ImmutableMap.<String, String>builder()
247 .put("actual-message-id", outputMsgId)
248 .put("expected-message-id", inputMsgId)
251 throw new NetconfDocumentedException("Response message contained unknown \"message-id\"",
252 null, NetconfDocumentedException.ErrorType.PROTOCOL,
253 NetconfDocumentedException.ErrorTag.BAD_ATTRIBUTE,
254 NetconfDocumentedException.ErrorSeverity.ERROR, errorInfo);
258 public static void checkSuccessReply(final NetconfMessage output) throws NetconfDocumentedException {
259 if (NetconfMessageUtil.isErrorMessage(output)) {
260 throw NetconfDocumentedException.fromXMLDocument(output.getDocument());
264 public static RpcError toRpcError(final NetconfDocumentedException ex) {
265 final StringBuilder infoBuilder = new StringBuilder();
266 final Map<String, String> errorInfo = ex.getErrorInfo();
267 if (errorInfo != null) {
268 for (final Entry<String, String> e : errorInfo.entrySet()) {
269 infoBuilder.append('<').append(e.getKey()).append('>').append(e.getValue())
270 .append("</").append(e.getKey()).append('>');
275 final ErrorSeverity severity = toRpcErrorSeverity(ex.getErrorSeverity());
276 return severity == ErrorSeverity.ERROR
277 ? RpcResultBuilder.newError(toRpcErrorType(ex.getErrorType()), ex.getErrorTag().getTagValue(),
278 ex.getLocalizedMessage(), null, infoBuilder.toString(), ex.getCause())
279 : RpcResultBuilder.newWarning(
280 toRpcErrorType(ex.getErrorType()), ex.getErrorTag().getTagValue(),
281 ex.getLocalizedMessage(), null, infoBuilder.toString(), ex.getCause());
284 private static ErrorSeverity toRpcErrorSeverity(final NetconfDocumentedException.ErrorSeverity severity) {
287 return RpcError.ErrorSeverity.WARNING;
289 return RpcError.ErrorSeverity.ERROR;
293 private static RpcError.ErrorType toRpcErrorType(final NetconfDocumentedException.ErrorType type) {
296 return RpcError.ErrorType.PROTOCOL;
298 return RpcError.ErrorType.RPC;
300 return RpcError.ErrorType.TRANSPORT;
302 return RpcError.ErrorType.APPLICATION;
306 public static NodeIdentifier toId(final PathArgument qname) {
307 return qname instanceof NodeIdentifier ? (NodeIdentifier) qname : toId(qname.getNodeType());
310 public static NodeIdentifier toId(final QName nodeType) {
311 return new NodeIdentifier(nodeType);
314 public static Element getDataSubtree(final Document doc) {
315 return (Element) doc.getElementsByTagNameNS(NETCONF_URI.toString(), "data").item(0);
318 public static boolean isDataRetrievalOperation(final QName rpc) {
319 return NETCONF_URI.equals(rpc.getNamespace())
320 && (NETCONF_GET_CONFIG_QNAME.getLocalName().equals(rpc.getLocalName())
321 || NETCONF_GET_QNAME.getLocalName().equals(rpc.getLocalName()));
324 public static ContainerSchemaNode createSchemaForDataRead(final SchemaContext schemaContext) {
325 return new NodeContainerProxy(NETCONF_DATA_QNAME, schemaContext.getChildNodes());
328 public static ContainerSchemaNode createSchemaForNotification(final NotificationDefinition next) {
329 return new NodeContainerProxy(next.getQName(), next.getChildNodes(), next.getAvailableAugmentations());
333 public static ContainerNode wrap(final QName name, final DataContainerChild<?, ?>... node) {
334 return wrap(toId(name), node);
337 public static ContainerNode wrap(final NodeIdentifier name, final DataContainerChild<?, ?>... node) {
338 return Builders.containerBuilder().withNodeIdentifier(name).withValue(ImmutableList.copyOf(node)).build();
341 public static AnyXmlNode createEditConfigAnyxml(
342 final SchemaContext ctx, final YangInstanceIdentifier dataPath,
343 final java.util.Optional<ModifyAction> operation,
344 final java.util.Optional<NormalizedNode<?, ?>> lastChildOverride) {
345 final NormalizedNode<?, ?> configContent;
347 if (dataPath.isEmpty()) {
348 Preconditions.checkArgument(lastChildOverride.isPresent(),
349 "Data has to be present when creating structure for top level element");
350 Preconditions.checkArgument(lastChildOverride.get() instanceof DataContainerChild<?, ?>,
351 "Data has to be either container or a list node when creating structure for top level element, "
352 + "but was: %s", lastChildOverride.get());
353 configContent = lastChildOverride.get();
355 final Entry<QName, ModifyAction> modifyOperation = operation.isPresent()
356 ? new AbstractMap.SimpleEntry<>(NETCONF_OPERATION_QNAME, operation.get()) : null;
357 configContent = ImmutableNodes.fromInstanceId(ctx, dataPath, lastChildOverride,
358 java.util.Optional.ofNullable(modifyOperation));
361 final Element element = XmlUtil.createElement(BLANK_DOCUMENT, NETCONF_CONFIG_QNAME.getLocalName(),
362 Optional.of(NETCONF_CONFIG_QNAME.getNamespace().toString()));
364 NetconfUtil.writeNormalizedNode(configContent, 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 public static DataContainerChild<?, ?> createEditConfigStructure(final SchemaContext ctx,
374 final YangInstanceIdentifier dataPath, final java.util.Optional<ModifyAction> operation,
375 final java.util.Optional<NormalizedNode<?, ?>> lastChildOverride) {
376 return Builders.choiceBuilder().withNodeIdentifier(EDIT_CONTENT_NODEID)
377 .withChild(createEditConfigAnyxml(ctx, dataPath, operation, lastChildOverride)).build();
380 public static SchemaPath toPath(final QName rpc) {
381 return SchemaPath.ROOT.createChild(rpc);
384 public static Map.Entry<Instant, XmlElement> stripNotification(final NetconfMessage message) {
385 final XmlElement xmlElement = XmlElement.fromDomDocument(message.getDocument());
386 final List<XmlElement> childElements = xmlElement.getChildElements();
387 Preconditions.checkArgument(childElements.size() == 2, "Unable to parse notification %s, unexpected format."
388 + "\nExpected 2 childElements, actual childElements size is %s", message, childElements.size());
390 final XmlElement eventTimeElement;
391 final XmlElement notificationElement;
393 if (childElements.get(0).getName().equals(EVENT_TIME)) {
394 eventTimeElement = childElements.get(0);
395 notificationElement = childElements.get(1);
396 } else if (childElements.get(1).getName().equals(EVENT_TIME)) {
397 eventTimeElement = childElements.get(1);
398 notificationElement = childElements.get(0);
400 throw new IllegalArgumentException("Notification payload does not contain " + EVENT_TIME + " " + message);
404 return new SimpleEntry<>(
405 NetconfNotification.RFC3339_DATE_PARSER.apply(eventTimeElement.getTextContent()).toInstant(),
406 notificationElement);
407 } catch (final DocumentedException e) {
408 throw new IllegalArgumentException("Notification payload does not contain " + EVENT_TIME + " " + message,
410 } catch (final DateTimeParseException e) {
411 LOG.warn("Unable to parse event time from {}. Setting time to {}", eventTimeElement,
412 NetconfNotification.UNKNOWN_EVENT_TIME, e);
413 return new SimpleEntry<>(NetconfNotification.UNKNOWN_EVENT_TIME.toInstant(),
414 notificationElement);
418 public static DOMResult prepareDomResultForRpcRequest(final QName rpcQName, final MessageCounter counter) {
419 final Document document = XmlUtil.newDocument();
420 final Element rpcNS =
421 document.createElementNS(NETCONF_RPC_QNAME.getNamespace().toString(), NETCONF_RPC_QNAME.getLocalName());
423 rpcNS.setAttribute(MESSAGE_ID_ATTR, counter.getNewMessageId(MESSAGE_ID_PREFIX));
424 final Element elementNS = document.createElementNS(rpcQName.getNamespace().toString(), rpcQName.getLocalName());
425 rpcNS.appendChild(elementNS);
426 document.appendChild(rpcNS);
427 return new DOMResult(elementNS);
430 public static DOMResult prepareDomResultForActionRequest(final DataSchemaContextTree dataSchemaContextTree,
431 final DOMDataTreeIdentifier domDataTreeIdentifier, final SchemaPath actionSchemaPath,
432 final MessageCounter counter, final String action) {
433 final Document document = XmlUtil.newDocument();
434 final Element rpcNS =
435 document.createElementNS(NETCONF_RPC_QNAME.getNamespace().toString(), NETCONF_RPC_QNAME.getLocalName());
437 rpcNS.setAttribute(MESSAGE_ID_ATTR, counter.getNewMessageId(MESSAGE_ID_PREFIX));
439 final Element actionNS = document.createElementNS(NETCONF_ACTION_NAMESPACE.toString(), NETCONF_ACTION);
440 final DataSchemaContextNode<?> rootSchemaContextNode = dataSchemaContextTree.getRoot();
441 final Element actionData = prepareActionData(rootSchemaContextNode, actionNS,
442 domDataTreeIdentifier.getRootIdentifier().getPathArguments().iterator(), document);
444 Element specificActionElement = document.createElement(action);
445 actionData.appendChild(specificActionElement);
446 rpcNS.appendChild(actionNS);
447 document.appendChild(rpcNS);
448 return new DOMResult(specificActionElement);
451 private static Element prepareActionData(final DataSchemaContextNode<?> currentParentSchemaNode,
452 final Element actionNS, final Iterator<PathArgument> iterator, final Document document) {
453 if (iterator.hasNext()) {
454 final PathArgument next = iterator.next();
455 final QName actualNS = next.getNodeType();
457 DataSchemaContextNode<?> current = currentParentSchemaNode.getChild(next);
458 Preconditions.checkArgument(current != null, "Invalid input: schema for argument %s not found", next);
460 if (current.isMixin()) {
461 return prepareActionData(current, actionNS, iterator, document);
464 final Element actualElement = document.createElementNS(actualNS.getNamespace().toString(),
465 actualNS.getLocalName());
466 if (next instanceof NodeWithValue) {
467 actualElement.setNodeValue(((NodeWithValue) next).getValue().toString());
468 } else if (next instanceof NodeIdentifierWithPredicates) {
469 for (Entry<QName, Object> entry : ((NodeIdentifierWithPredicates) next).getKeyValues().entrySet()) {
470 final Element entryElement = document.createElementNS(entry.getKey().getNamespace().toString(),
471 entry.getKey().getLocalName());
472 entryElement.setTextContent(entry.getValue().toString());
473 entryElement.setNodeValue(entry.getValue().toString());
474 actualElement.appendChild(entryElement);
477 actionNS.appendChild(actualElement);
478 return prepareActionData(current, actualElement, iterator, document);
484 @SuppressWarnings("checkstyle:IllegalCatch")
485 public static void writeNormalizedRpc(final ContainerNode normalized, final DOMResult result,
486 final SchemaPath schemaPath,
487 final SchemaContext baseNetconfCtx) throws IOException, XMLStreamException {
488 final XMLStreamWriter writer = NetconfUtil.XML_FACTORY.createXMLStreamWriter(result);
490 try (NormalizedNodeStreamWriter normalizedNodeStreamWriter =
491 XMLStreamNormalizedNodeStreamWriter.create(writer, baseNetconfCtx, schemaPath)) {
492 try (SchemaOrderedNormalizedNodeWriter normalizedNodeWriter =
493 new SchemaOrderedNormalizedNodeWriter(normalizedNodeStreamWriter, baseNetconfCtx, schemaPath)) {
494 final Collection<DataContainerChild<?, ?>> value = normalized.getValue();
495 normalizedNodeWriter.write(value);
496 normalizedNodeWriter.flush();
502 } catch (final Exception e) {
503 LOG.warn("Unable to close resource properly", e);
508 public static RpcResult<NetconfMessage> toRpcResult(final FailedNetconfMessage message) {
509 return RpcResultBuilder.<NetconfMessage>failed()
512 new NetconfDocumentedException(
513 message.getException().getMessage(),
514 DocumentedException.ErrorType.APPLICATION,
515 DocumentedException.ErrorTag.MALFORMED_MESSAGE,
516 DocumentedException.ErrorSeverity.ERROR)))