2 * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
4 * This program and the accompanying materials are made available under the
5 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6 * and is available at http://www.eclipse.org/legal/epl-v10.html
8 package org.opendaylight.netconf.sal.connect.netconf.util;
10 import static org.opendaylight.netconf.util.NetconfUtil.NETCONF_DATA_QNAME;
11 import static org.opendaylight.netconf.util.NetconfUtil.NETCONF_QNAME;
13 import com.google.common.base.Preconditions;
14 import com.google.common.collect.ImmutableList;
15 import com.google.common.collect.ImmutableMap;
16 import java.io.IOException;
18 import java.time.Instant;
19 import java.time.format.DateTimeParseException;
20 import java.util.AbstractMap.SimpleEntry;
21 import java.util.ArrayDeque;
22 import java.util.Collection;
23 import java.util.Deque;
24 import java.util.Iterator;
25 import java.util.List;
26 import java.util.Locale;
28 import java.util.Map.Entry;
29 import java.util.Optional;
30 import javax.xml.stream.XMLStreamException;
31 import javax.xml.stream.XMLStreamWriter;
32 import javax.xml.transform.dom.DOMResult;
33 import javax.xml.transform.dom.DOMSource;
34 import org.opendaylight.mdsal.dom.api.DOMDataTreeIdentifier;
35 import org.opendaylight.netconf.api.DocumentedException;
36 import org.opendaylight.netconf.api.FailedNetconfMessage;
37 import org.opendaylight.netconf.api.ModifyAction;
38 import org.opendaylight.netconf.api.NetconfDocumentedException;
39 import org.opendaylight.netconf.api.NetconfMessage;
40 import org.opendaylight.netconf.api.xml.XmlElement;
41 import org.opendaylight.netconf.api.xml.XmlUtil;
42 import org.opendaylight.netconf.notifications.NetconfNotification;
43 import org.opendaylight.netconf.sal.connect.util.MessageCounter;
44 import org.opendaylight.netconf.util.NetconfUtil;
45 import org.opendaylight.netconf.util.NodeContainerProxy;
46 import org.opendaylight.netconf.util.messages.NetconfMessageUtil;
47 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netconf.base._1._0.rev110601.edit.config.input.EditContent;
48 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netconf.notification._1._0.rev080714.CreateSubscriptionInput;
49 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.monitoring.rev101004.NetconfState;
50 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.notifications.rev120206.NetconfCapabilityChange;
51 import org.opendaylight.yangtools.rfc7952.data.api.NormalizedMetadata;
52 import org.opendaylight.yangtools.rfc7952.data.util.ImmutableNormalizedMetadata;
53 import org.opendaylight.yangtools.rfc7952.data.util.ImmutableNormalizedMetadata.Builder;
54 import org.opendaylight.yangtools.yang.common.QName;
55 import org.opendaylight.yangtools.yang.common.RpcError;
56 import org.opendaylight.yangtools.yang.common.RpcError.ErrorSeverity;
57 import org.opendaylight.yangtools.yang.common.RpcResult;
58 import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
59 import org.opendaylight.yangtools.yang.common.YangConstants;
60 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
61 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
62 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
63 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeWithValue;
64 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
65 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
66 import org.opendaylight.yangtools.yang.data.api.schema.DOMSourceAnyxmlNode;
67 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
68 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
69 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
70 import org.opendaylight.yangtools.yang.data.codec.xml.XMLStreamNormalizedNodeStreamWriter;
71 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
72 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
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.ContainerSchemaNode;
77 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
78 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
79 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
80 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
81 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier.Absolute;
82 import org.slf4j.Logger;
83 import org.slf4j.LoggerFactory;
84 import org.w3c.dom.Document;
85 import org.w3c.dom.Element;
87 public final class NetconfMessageTransformUtil {
89 private static final Logger LOG = LoggerFactory.getLogger(NetconfMessageTransformUtil.class);
91 public static final String MESSAGE_ID_PREFIX = "m";
92 public static final String MESSAGE_ID_ATTR = "message-id";
94 public static final QName CREATE_SUBSCRIPTION_RPC_QNAME =
95 QName.create(CreateSubscriptionInput.QNAME, "create-subscription").intern();
96 private static final String SUBTREE = "subtree";
98 // Blank document used for creation of new DOM nodes
99 private static final Document BLANK_DOCUMENT = XmlUtil.newDocument();
100 public static final String EVENT_TIME = "eventTime";
102 private NetconfMessageTransformUtil() {
106 public static final QName IETF_NETCONF_MONITORING =
107 QName.create(NetconfState.QNAME, "ietf-netconf-monitoring").intern();
108 public static final QName GET_DATA_QNAME = QName.create(IETF_NETCONF_MONITORING, "data").intern();
109 public static final QName GET_SCHEMA_QNAME = QName.create(IETF_NETCONF_MONITORING, "get-schema").intern();
110 public static final QName IETF_NETCONF_MONITORING_SCHEMA_FORMAT =
111 QName.create(IETF_NETCONF_MONITORING, "format").intern();
112 public static final QName IETF_NETCONF_MONITORING_SCHEMA_LOCATION =
113 QName.create(IETF_NETCONF_MONITORING, "location").intern();
114 public static final QName IETF_NETCONF_MONITORING_SCHEMA_IDENTIFIER =
115 QName.create(IETF_NETCONF_MONITORING, "identifier").intern();
116 public static final QName IETF_NETCONF_MONITORING_SCHEMA_VERSION =
117 QName.create(IETF_NETCONF_MONITORING, "version").intern();
118 public static final QName IETF_NETCONF_MONITORING_SCHEMA_NAMESPACE =
119 QName.create(IETF_NETCONF_MONITORING, "namespace").intern();
121 public static final QName IETF_NETCONF_NOTIFICATIONS =
122 QName.create(NetconfCapabilityChange.QNAME, "ietf-netconf-notifications").intern();
124 public static final URI NETCONF_URI = NETCONF_QNAME.getNamespace();
126 public static final NodeIdentifier NETCONF_DATA_NODEID = NodeIdentifier.create(NETCONF_DATA_QNAME);
128 public static final QName NETCONF_RPC_REPLY_QNAME = QName.create(NETCONF_QNAME, "rpc-reply").intern();
129 public static final NodeIdentifier NETCONF_RPC_REPLY_NODEID = NodeIdentifier.create(NETCONF_RPC_REPLY_QNAME);
131 public static final QName NETCONF_OK_QNAME = QName.create(NETCONF_QNAME, "ok").intern();
132 public static final QName NETCONF_ERROR_OPTION_QNAME = QName.create(NETCONF_QNAME, "error-option").intern();
133 public static final NodeIdentifier NETCONF_ERROR_OPTION_NODEID = NodeIdentifier.create(NETCONF_ERROR_OPTION_QNAME);
134 public static final QName NETCONF_RUNNING_QNAME = QName.create(NETCONF_QNAME, "running").intern();
135 public static final QName NETCONF_SOURCE_QNAME = QName.create(NETCONF_QNAME, "source").intern();
136 public static final NodeIdentifier NETCONF_SOURCE_NODEID = NodeIdentifier.create(NETCONF_SOURCE_QNAME);
137 public static final QName NETCONF_CANDIDATE_QNAME = QName.create(NETCONF_QNAME, "candidate").intern();
138 public static final QName NETCONF_TARGET_QNAME = QName.create(NETCONF_QNAME, "target").intern();
139 public static final NodeIdentifier NETCONF_TARGET_NODEID = NodeIdentifier.create(NETCONF_TARGET_QNAME);
140 public static final QName NETCONF_CONFIG_QNAME = QName.create(NETCONF_QNAME, "config").intern();
141 public static final NodeIdentifier NETCONF_CONFIG_NODEID = NodeIdentifier.create(NETCONF_CONFIG_QNAME);
143 public static final QName NETCONF_COMMIT_QNAME = QName.create(NETCONF_QNAME, "commit").intern();
144 public static final SchemaPath NETCONF_COMMIT_PATH = toPath(NETCONF_COMMIT_QNAME);
145 public static final QName NETCONF_VALIDATE_QNAME = QName.create(NETCONF_QNAME, "validate").intern();
146 public static final NodeIdentifier NETCONF_VALIDATE_NODEID = NodeIdentifier.create(NETCONF_VALIDATE_QNAME);
147 public static final SchemaPath NETCONF_VALIDATE_PATH = toPath(NETCONF_VALIDATE_QNAME);
148 public static final QName NETCONF_COPY_CONFIG_QNAME = QName.create(NETCONF_QNAME, "copy-config").intern();
149 public static final NodeIdentifier NETCONF_COPY_CONFIG_NODEID = NodeIdentifier.create(NETCONF_COPY_CONFIG_QNAME);
150 public static final SchemaPath NETCONF_COPY_CONFIG_PATH = toPath(NETCONF_COPY_CONFIG_QNAME);
152 public static final QName NETCONF_OPERATION_QNAME = QName.create(NETCONF_QNAME, "operation").intern();
153 private static final QName NETCONF_OPERATION_QNAME_LEGACY = NETCONF_OPERATION_QNAME.withoutRevision().intern();
154 public static final QName NETCONF_DEFAULT_OPERATION_QNAME =
155 QName.create(NETCONF_OPERATION_QNAME, "default-operation").intern();
156 public static final NodeIdentifier NETCONF_DEFAULT_OPERATION_NODEID =
157 NodeIdentifier.create(NETCONF_DEFAULT_OPERATION_QNAME);
158 public static final QName NETCONF_EDIT_CONFIG_QNAME = QName.create(NETCONF_QNAME, "edit-config").intern();
159 public static final NodeIdentifier NETCONF_EDIT_CONFIG_NODEID = NodeIdentifier.create(NETCONF_EDIT_CONFIG_QNAME);
160 public static final SchemaPath NETCONF_EDIT_CONFIG_PATH = toPath(NETCONF_EDIT_CONFIG_QNAME);
161 public static final QName NETCONF_GET_CONFIG_QNAME = QName.create(NETCONF_QNAME, "get-config");
162 public static final NodeIdentifier NETCONF_GET_CONFIG_NODEID = NodeIdentifier.create(NETCONF_GET_CONFIG_QNAME);
163 public static final SchemaPath NETCONF_GET_CONFIG_PATH = toPath(NETCONF_GET_CONFIG_QNAME);
164 public static final QName NETCONF_DISCARD_CHANGES_QNAME = QName.create(NETCONF_QNAME, "discard-changes");
165 public static final SchemaPath NETCONF_DISCARD_CHANGES_PATH = toPath(NETCONF_DISCARD_CHANGES_QNAME);
166 public static final QName NETCONF_TYPE_QNAME = QName.create(NETCONF_QNAME, "type").intern();
167 public static final QName NETCONF_FILTER_QNAME = QName.create(NETCONF_QNAME, "filter").intern();
168 public static final QName NETCONF_GET_QNAME = QName.create(NETCONF_QNAME, "get").intern();
169 public static final NodeIdentifier NETCONF_GET_NODEID = NodeIdentifier.create(NETCONF_GET_QNAME);
170 public static final SchemaPath NETCONF_GET_PATH = toPath(NETCONF_GET_QNAME);
171 public static final QName NETCONF_RPC_QNAME = QName.create(NETCONF_QNAME, "rpc").intern();
172 public static final QName YANG_QNAME = null;
173 public static final URI NETCONF_ACTION_NAMESPACE = URI.create("urn:ietf:params:xml:ns:yang:1");
174 public static final String NETCONF_ACTION = "action";
176 public static final URI NETCONF_ROLLBACK_ON_ERROR_URI = URI
177 .create("urn:ietf:params:netconf:capability:rollback-on-error:1.0");
178 public static final String ROLLBACK_ON_ERROR_OPTION = "rollback-on-error";
180 public static final URI NETCONF_CANDIDATE_URI = URI
181 .create("urn:ietf:params:netconf:capability:candidate:1.0");
183 public static final URI NETCONF_NOTIFICATONS_URI = URI
184 .create("urn:ietf:params:netconf:capability:notification:1.0");
186 public static final URI NETCONF_RUNNING_WRITABLE_URI = URI
187 .create("urn:ietf:params:netconf:capability:writable-running:1.0");
189 public static final QName NETCONF_LOCK_QNAME = QName.create(NETCONF_QNAME, "lock").intern();
190 public static final NodeIdentifier NETCONF_LOCK_NODEID = NodeIdentifier.create(NETCONF_LOCK_QNAME);
191 public static final SchemaPath NETCONF_LOCK_PATH = toPath(NETCONF_LOCK_QNAME);
192 public static final QName NETCONF_UNLOCK_QNAME = QName.create(NETCONF_QNAME, "unlock").intern();
193 public static final NodeIdentifier NETCONF_UNLOCK_NODEID = NodeIdentifier.create(NETCONF_UNLOCK_QNAME);
194 public static final SchemaPath NETCONF_UNLOCK_PATH = toPath(NETCONF_UNLOCK_QNAME);
196 public static final NodeIdentifier EDIT_CONTENT_NODEID = NodeIdentifier.create(EditContent.QNAME);
198 // Discard changes message
199 public static final ContainerNode DISCARD_CHANGES_RPC_CONTENT = Builders.containerBuilder()
200 .withNodeIdentifier(NodeIdentifier.create(NETCONF_DISCARD_CHANGES_QNAME)).build();
202 // Commit changes message
203 public static final ContainerNode COMMIT_RPC_CONTENT = Builders.containerBuilder()
204 .withNodeIdentifier(NodeIdentifier.create(NETCONF_COMMIT_QNAME)).build();
207 public static final ContainerNode GET_RPC_CONTENT = Builders.containerBuilder()
208 .withNodeIdentifier(NETCONF_GET_NODEID).build();
210 // Create-subscription changes message
211 public static final ContainerNode CREATE_SUBSCRIPTION_RPC_CONTENT = Builders.containerBuilder()
212 .withNodeIdentifier(NodeIdentifier.create(CREATE_SUBSCRIPTION_RPC_QNAME)).build();
214 public static final SchemaPath CREATE_SUBSCRIPTION_RPC_PATH = toPath(CREATE_SUBSCRIPTION_RPC_QNAME);
216 public static final NodeIdentifier NETCONF_FILTER_NODEID = NodeIdentifier.create(NETCONF_FILTER_QNAME);
218 public static final DataContainerChild<?, ?> EMPTY_FILTER;
221 final Element element = XmlUtil.createElement(BLANK_DOCUMENT, NETCONF_FILTER_QNAME.getLocalName(),
222 Optional.of(NETCONF_FILTER_QNAME.getNamespace().toString()));
223 element.setAttributeNS(NETCONF_FILTER_QNAME.getNamespace().toString(),
224 NETCONF_TYPE_QNAME.getLocalName(), SUBTREE);
226 EMPTY_FILTER = Builders.anyXmlBuilder().withNodeIdentifier(NETCONF_FILTER_NODEID)
227 .withValue(new DOMSource(element)).build();
230 public static DataContainerChild<?, ?> toFilterStructure(final YangInstanceIdentifier identifier,
231 final EffectiveModelContext ctx) {
232 final Element element = XmlUtil.createElement(BLANK_DOCUMENT, NETCONF_FILTER_QNAME.getLocalName(),
233 Optional.of(NETCONF_FILTER_QNAME.getNamespace().toString()));
234 element.setAttributeNS(NETCONF_FILTER_QNAME.getNamespace().toString(), NETCONF_TYPE_QNAME.getLocalName(),
238 NetconfUtil.writeFilter(identifier, new DOMResult(element), SchemaPath.ROOT, ctx);
239 } catch (IOException | XMLStreamException e) {
240 throw new IllegalStateException("Unable to serialize filter element for path " + identifier, e);
243 return Builders.anyXmlBuilder().withNodeIdentifier(NETCONF_FILTER_NODEID).withValue(new DOMSource(element))
247 public static void checkValidReply(final NetconfMessage input, final NetconfMessage output)
248 throws NetconfDocumentedException {
249 final String inputMsgId = input.getDocument().getDocumentElement().getAttribute(MESSAGE_ID_ATTR);
250 final String outputMsgId = output.getDocument().getDocumentElement().getAttribute(MESSAGE_ID_ATTR);
252 if (!inputMsgId.equals(outputMsgId)) {
253 final Map<String, String> errorInfo = ImmutableMap.<String, String>builder()
254 .put("actual-message-id", outputMsgId)
255 .put("expected-message-id", inputMsgId)
258 throw new NetconfDocumentedException("Response message contained unknown \"message-id\"",
259 null, NetconfDocumentedException.ErrorType.PROTOCOL,
260 NetconfDocumentedException.ErrorTag.BAD_ATTRIBUTE,
261 NetconfDocumentedException.ErrorSeverity.ERROR, errorInfo);
265 public static void checkSuccessReply(final NetconfMessage output) throws NetconfDocumentedException {
266 if (NetconfMessageUtil.isErrorMessage(output)) {
267 throw NetconfDocumentedException.fromXMLDocument(output.getDocument());
271 public static RpcError toRpcError(final NetconfDocumentedException ex) {
272 final StringBuilder infoBuilder = new StringBuilder();
273 final Map<String, String> errorInfo = ex.getErrorInfo();
274 if (errorInfo != null) {
275 for (final Entry<String, String> e : errorInfo.entrySet()) {
276 infoBuilder.append('<').append(e.getKey()).append('>').append(e.getValue())
277 .append("</").append(e.getKey()).append('>');
282 final ErrorSeverity severity = toRpcErrorSeverity(ex.getErrorSeverity());
283 return severity == ErrorSeverity.ERROR
284 ? RpcResultBuilder.newError(toRpcErrorType(ex.getErrorType()), ex.getErrorTag().getTagValue(),
285 ex.getLocalizedMessage(), null, infoBuilder.toString(), ex.getCause())
286 : RpcResultBuilder.newWarning(
287 toRpcErrorType(ex.getErrorType()), ex.getErrorTag().getTagValue(),
288 ex.getLocalizedMessage(), null, infoBuilder.toString(), ex.getCause());
291 private static ErrorSeverity toRpcErrorSeverity(final NetconfDocumentedException.ErrorSeverity severity) {
294 return RpcError.ErrorSeverity.WARNING;
296 return RpcError.ErrorSeverity.ERROR;
300 private static RpcError.ErrorType toRpcErrorType(final NetconfDocumentedException.ErrorType type) {
303 return RpcError.ErrorType.PROTOCOL;
305 return RpcError.ErrorType.RPC;
307 return RpcError.ErrorType.TRANSPORT;
309 return RpcError.ErrorType.APPLICATION;
313 public static NodeIdentifier toId(final PathArgument qname) {
314 return qname instanceof NodeIdentifier ? (NodeIdentifier) qname : toId(qname.getNodeType());
317 public static NodeIdentifier toId(final QName nodeType) {
318 return new NodeIdentifier(nodeType);
321 public static Element getDataSubtree(final Document doc) {
322 return (Element) doc.getElementsByTagNameNS(NETCONF_URI.toString(), "data").item(0);
325 public static boolean isDataRetrievalOperation(final QName rpc) {
326 return NETCONF_URI.equals(rpc.getNamespace())
327 && (NETCONF_GET_CONFIG_QNAME.getLocalName().equals(rpc.getLocalName())
328 || NETCONF_GET_QNAME.getLocalName().equals(rpc.getLocalName()));
331 public static ContainerSchemaNode createSchemaForDataRead(final SchemaContext schemaContext) {
332 return new NodeContainerProxy(NETCONF_DATA_QNAME, schemaContext.getChildNodes());
335 public static ContainerSchemaNode createSchemaForNotification(final NotificationDefinition next) {
336 return new NodeContainerProxy(next.getQName(), next.getChildNodes(), next.getAvailableAugmentations());
340 public static ContainerNode wrap(final QName name, final DataContainerChild<?, ?>... node) {
341 return wrap(toId(name), node);
344 public static ContainerNode wrap(final NodeIdentifier name, final DataContainerChild<?, ?>... node) {
345 return Builders.containerBuilder().withNodeIdentifier(name).withValue(ImmutableList.copyOf(node)).build();
348 public static DOMSourceAnyxmlNode createEditConfigAnyxml(
349 final EffectiveModelContext ctx, final YangInstanceIdentifier dataPath,
350 final Optional<ModifyAction> operation,
351 final Optional<NormalizedNode<?, ?>> lastChildOverride) {
352 final NormalizedNode<?, ?> configContent;
353 final NormalizedMetadata metadata;
354 if (dataPath.isEmpty()) {
355 Preconditions.checkArgument(lastChildOverride.isPresent(),
356 "Data has to be present when creating structure for top level element");
357 Preconditions.checkArgument(lastChildOverride.get() instanceof DataContainerChild<?, ?>,
358 "Data has to be either container or a list node when creating structure for top level element, "
359 + "but was: %s", lastChildOverride.get());
360 configContent = lastChildOverride.get();
363 configContent = ImmutableNodes.fromInstanceId(ctx, dataPath, lastChildOverride);
364 metadata = operation.map(oper -> leafMetadata(dataPath, oper)).orElse(null);
367 final Element element = XmlUtil.createElement(BLANK_DOCUMENT, NETCONF_CONFIG_QNAME.getLocalName(),
368 Optional.of(NETCONF_CONFIG_QNAME.getNamespace().toString()));
371 NetconfUtil.writeNormalizedNode(configContent, metadata, new DOMResult(element), SchemaPath.ROOT, ctx);
372 } catch (IOException | XMLStreamException e) {
373 throw new IllegalStateException("Unable to serialize edit config content element for path " + dataPath, e);
376 return Builders.anyXmlBuilder().withNodeIdentifier(NETCONF_CONFIG_NODEID).withValue(new DOMSource(element))
380 private static NormalizedMetadata leafMetadata(final YangInstanceIdentifier path, final ModifyAction oper) {
381 final List<PathArgument> args = path.getPathArguments();
382 final Deque<Builder> builders = new ArrayDeque<>(args.size());
384 // Step one: open builders
385 for (PathArgument arg : args) {
386 builders.push(ImmutableNormalizedMetadata.builder().withIdentifier(arg));
389 // Step two: set the top builder's metadata
390 builders.peek().withAnnotation(NETCONF_OPERATION_QNAME_LEGACY, oper.toString().toLowerCase(Locale.US));
392 // Step three: build the tree
394 final ImmutableNormalizedMetadata currentMeta = builders.pop().build();
395 final Builder parent = builders.peek();
396 if (parent != null) {
397 parent.withChild(currentMeta);
404 public static DataContainerChild<?, ?> createEditConfigStructure(final EffectiveModelContext ctx,
405 final YangInstanceIdentifier dataPath, final Optional<ModifyAction> operation,
406 final Optional<NormalizedNode<?, ?>> lastChildOverride) {
407 return Builders.choiceBuilder().withNodeIdentifier(EDIT_CONTENT_NODEID)
408 .withChild(createEditConfigAnyxml(ctx, dataPath, operation, lastChildOverride)).build();
411 public static SchemaPath toPath(final QName rpc) {
412 return SchemaPath.ROOT.createChild(rpc);
415 public static Map.Entry<Instant, XmlElement> stripNotification(final NetconfMessage message) {
416 final XmlElement xmlElement = XmlElement.fromDomDocument(message.getDocument());
417 final List<XmlElement> childElements = xmlElement.getChildElements();
418 Preconditions.checkArgument(childElements.size() == 2, "Unable to parse notification %s, unexpected format."
419 + "\nExpected 2 childElements, actual childElements size is %s", message, childElements.size());
421 final XmlElement eventTimeElement;
422 final XmlElement notificationElement;
424 if (childElements.get(0).getName().equals(EVENT_TIME)) {
425 eventTimeElement = childElements.get(0);
426 notificationElement = childElements.get(1);
427 } else if (childElements.get(1).getName().equals(EVENT_TIME)) {
428 eventTimeElement = childElements.get(1);
429 notificationElement = childElements.get(0);
431 throw new IllegalArgumentException("Notification payload does not contain " + EVENT_TIME + " " + message);
435 return new SimpleEntry<>(
436 NetconfNotification.RFC3339_DATE_PARSER.apply(eventTimeElement.getTextContent()).toInstant(),
437 notificationElement);
438 } catch (final DocumentedException e) {
439 throw new IllegalArgumentException("Notification payload does not contain " + EVENT_TIME + " " + message,
441 } catch (final DateTimeParseException e) {
442 LOG.warn("Unable to parse event time from {}. Setting time to {}", eventTimeElement,
443 NetconfNotification.UNKNOWN_EVENT_TIME, e);
444 return new SimpleEntry<>(NetconfNotification.UNKNOWN_EVENT_TIME.toInstant(),
445 notificationElement);
449 public static DOMResult prepareDomResultForRpcRequest(final QName rpcQName, final MessageCounter counter) {
450 final Document document = XmlUtil.newDocument();
451 final Element rpcNS =
452 document.createElementNS(NETCONF_RPC_QNAME.getNamespace().toString(), NETCONF_RPC_QNAME.getLocalName());
454 rpcNS.setAttribute(MESSAGE_ID_ATTR, counter.getNewMessageId(MESSAGE_ID_PREFIX));
455 final Element elementNS = document.createElementNS(rpcQName.getNamespace().toString(), rpcQName.getLocalName());
456 rpcNS.appendChild(elementNS);
457 document.appendChild(rpcNS);
458 return new DOMResult(elementNS);
461 public static DOMResult prepareDomResultForActionRequest(final DataSchemaContextTree dataSchemaContextTree,
462 final DOMDataTreeIdentifier domDataTreeIdentifier, final MessageCounter counter, final QName action) {
463 final Document document = XmlUtil.newDocument();
464 final Element rpcNS =
465 document.createElementNS(NETCONF_RPC_QNAME.getNamespace().toString(), NETCONF_RPC_QNAME.getLocalName());
467 rpcNS.setAttribute(MESSAGE_ID_ATTR, counter.getNewMessageId(MESSAGE_ID_PREFIX));
469 final Element actionNS = document.createElementNS(NETCONF_ACTION_NAMESPACE.toString(), NETCONF_ACTION);
470 final DataSchemaContextNode<?> rootSchemaContextNode = dataSchemaContextTree.getRoot();
471 final Element actionData = prepareActionData(rootSchemaContextNode, actionNS,
472 domDataTreeIdentifier.getRootIdentifier().getPathArguments().iterator(), document);
474 final Element specificActionElement =
475 document.createElementNS(action.getNamespace().toString(), action.getLocalName());
476 actionData.appendChild(specificActionElement);
477 rpcNS.appendChild(actionNS);
478 document.appendChild(rpcNS);
479 return new DOMResult(specificActionElement);
482 private static Element prepareActionData(final DataSchemaContextNode<?> currentParentSchemaNode,
483 final Element actionNS, final Iterator<PathArgument> iterator, final Document document) {
484 if (iterator.hasNext()) {
485 final PathArgument next = iterator.next();
487 final DataSchemaContextNode<?> current = currentParentSchemaNode.getChild(next);
488 Preconditions.checkArgument(current != null, "Invalid input: schema for argument %s not found", next);
490 if (current.isMixin()) {
491 return prepareActionData(current, actionNS, iterator, document);
494 final QName actualNS = next.getNodeType();
495 final Element actualElement = document.createElementNS(actualNS.getNamespace().toString(),
496 actualNS.getLocalName());
497 if (next instanceof NodeWithValue) {
498 actualElement.setNodeValue(((NodeWithValue) next).getValue().toString());
499 } else if (next instanceof NodeIdentifierWithPredicates) {
500 for (Entry<QName, Object> entry : ((NodeIdentifierWithPredicates) next).entrySet()) {
501 final Element entryElement = document.createElementNS(entry.getKey().getNamespace().toString(),
502 entry.getKey().getLocalName());
503 entryElement.setTextContent(entry.getValue().toString());
504 entryElement.setNodeValue(entry.getValue().toString());
505 actualElement.appendChild(entryElement);
508 actionNS.appendChild(actualElement);
509 return prepareActionData(current, actualElement, iterator, document);
515 @SuppressWarnings("checkstyle:IllegalCatch")
516 public static void writeNormalizedOperationInput(final ContainerNode normalized, final DOMResult result,
517 final Absolute operationPath, final EffectiveModelContext baseNetconfCtx)
518 throws IOException, XMLStreamException {
519 final QName inputQName = YangConstants.operationInputQName(operationPath.lastNodeIdentifier().getModule());
520 // FIXME: eliminate this conversion
521 final SchemaPath inputPath = operationPath.asSchemaPath().createChild(inputQName);
523 final XMLStreamWriter writer = NetconfUtil.XML_FACTORY.createXMLStreamWriter(result);
525 try (NormalizedNodeStreamWriter normalizedNodeStreamWriter =
526 XMLStreamNormalizedNodeStreamWriter.create(writer, baseNetconfCtx, inputPath)) {
527 try (SchemaOrderedNormalizedNodeWriter normalizedNodeWriter =
528 new SchemaOrderedNormalizedNodeWriter(normalizedNodeStreamWriter, baseNetconfCtx, inputPath)) {
529 final Collection<DataContainerChild<?, ?>> value = normalized.getValue();
530 normalizedNodeWriter.write(value);
531 normalizedNodeWriter.flush();
537 } catch (final Exception e) {
538 LOG.warn("Unable to close resource properly", e);
543 public static RpcResult<NetconfMessage> toRpcResult(final FailedNetconfMessage message) {
544 return RpcResultBuilder.<NetconfMessage>failed()
547 new NetconfDocumentedException(
548 message.getException().getMessage(),
549 DocumentedException.ErrorType.APPLICATION,
550 DocumentedException.ErrorTag.MALFORMED_MESSAGE,
551 DocumentedException.ErrorSeverity.ERROR)))